PHP triggering mail functions at a set time and date - php

I want to check the stock level every day at a certain time (say 11pm GMT) and email a list of items that are low on stock to the admin. I have managed to get the mailing function working but I am struggling to limit the checks to once a day (right now it sends an email to the admin email every time the page loads)
Your help will be much appreciated!

I think that you just need to put your script in a separate file and run once per day with a cron job
You might want to read more about cron jobs in this post How to create cron job using PHP?

In case that impossible to run a cron job, you can save last mail time in DB or file and check timeout on page load.

Related

How to execute some code on a specific datetime to the second?

I'm building a market place with auctions. I need to end auctions preferably at the exact second they are defined to end according to their record in the mysql database.
I know about CRON jobs and I'm currently running a CRON job every minute to execute some script which checks if there are sales that should end.
However this sometimes means that an auction ends almost a minute too late, which is not acceptable. Does anybody know how to make this more accurate without putting a lot of load on the server? For example I wouldn't want to run a script every second to check if sales have ended.
Check timestamp everytime a user try to click auctions button. So even the page haven't refresh and times up, user is not able to bid your item.

How to run a PHP script automatically in every month

I have the php project for user can register and buy the hours to listen music or video, the not used of 50% hours have to rollover to next month, I wanted to automate this process when user complete one month I have to check their usage and process the rollover using php. I have following user details on DB, Signed-up date with time and usage and hours they purchased and used hours. I want to do it once in a month for each customer.
Is it possible using cron jobs? I don't have any idea to do this.
Not sure if this is the right approach but I've been running such kind of scripts when a user logs into his account.
For example.
You can do something like on successful login request by the user
if(date of buying hours has crossed the specified limit) /here you can check for expiry date/
{ // run your script here
}
else{}
just a suggestion!
You don't need to update all of the records all at once. Just update it for the user who logs in.
At the end, it will be updated for every user I think.
yes this possible with Cron Job 1st Create your php file with your condition use update query then add this cron job file in your server Cron Job Section and select date when you want to run this file. in cron job just file your cronjobfile.php name , Date and time when this file run.
Short answer: Use Cron job.
Syntax and usage of how to use it is almost straight forward. Here's a cheat sheet.
Note: If you're on a shared host, some hosts don't allow you to use cron job.
Edit: What #Havenard suggested is correct. The below cron job will visit the url once at minute 00 of every hour:
0 * * * * wget http://www.mywebsite.com/some/link

Are wordpress cron jobs executed sequentially or in parallel?

I am trying to limit the number of emails sent from my website to cope with the hosting service email limitations.
I am using cron jobs and an indicator of piling the emails in the database to check if the number of emails sent is approaching the limit of max emails sent.
The way I do that, is by directly executing the scheduled process then make it 'sleep' for a certain period of time (according to its position in the queue) and then send the email and log in the database.
To explain further the reason why I am using scheduled tasks and 'sleep', consider the scenario below:
A user tries to register to my website and expects an email to be sent to him/her shortly. Thus, if the emails/minute quota is exceeded, I need to send a different message: "Our server is busy, please permit 'x' minutes to perform the required task".
The requests to send email are all done through AJAX. Using 'sleep' within the process itself is not an option because the user will have to wait the x minutes until the 'busy message' is echo'd.
I tried with ob_flush, flush...etc. combinations to echo the message then the server works out everything in the background, but that never worked. The AJAX call was always waiting for the script to end to echo the result.
I need multi-threading in the single-threaded PHP language! As a workaround I used cron jobs, where each piled email is scheduled to be executed at time() (i.e. directly fire the scheduled job) which is hooked to the same function that sends emails. Using a flag, the function knows that the request is a piled email and makes it 'sleep' until the time required for the email quota reset.
The problem: If 5 people registered at almost the same time (while we still have an email pile), then we have 5 cron jobs that should all be executed at the same time and then sleep for a while (the sleep time can differ if the number of emails in the pile are already greater than the email quota), then emails are sent. However, when I check the logs in the database, I find that the scheduled jobs are executed sequentially and not in parallel. Sometimes it happens a cron job is fired before the other ends, but they don't fire at the same time.
I know that wordpress cron jobs are not really cron jobs and are fired once somebody visits the website (and I make sure I refresh the pages after the registration requests are sent to fire all of the scheduled tasks), but they seem to be the only option for me since my hosting server doesn't allow access to the server neither allows scheduling cron jobs.
Here is part of the code that executes the above:
//Test example to pile up emails, where quota is set to 2 emails every 30 seconds
$Emails_Threshold = 2;
$Threshold_Duration = 0.5*60;
//Get email indicator info
$Email_Info = $wpdb->get_row(
"SELECT *
FROM PileEmails
WHERE priority = -1
AND Status='New';"
,ARRAY_A);
if ($sleep ==0 && $Queue_Info_id==0){ //Not a scheduled event
//Check if there are queued emails
$Queue_exist = $wpdb->get_row (
$wpdb->prepare("
SELECT Status
FROM PileEmails
WHERE Status='Queued';"
,$mail_priority)
,ARRAY_A);
if (!empty($Queue_exist) || ($Email_Info['last_email_time'] > (time()-$Threshold_Duration))){
if ($Email_Info['count_emails']>=$Emails_Threshold){
//Code to Pile up
}
}else{
//Reset email counter
}
}else{
$wpdb->insert( "PileEmails",$Sleep_Info,$format);
sleep(10); //10 seconds here just as an example
}
//Code to send emails
Here is what I get logged into the database when I try to send 10 emails after exceeding the quota.
Notice that the time stamp has 10 seconds difference between each log and the following one although they should all be fired at the same time and each sleeps for 10 seconds then all send emails in parallel.
So my question is: Why does wordpress cron fire the scheduled jobs sequentially and not in parallel? and how to overcome this problem?
Any help is much appreciated.
As mentioned, installing a cron plugin will help to manage your crons.
To answer your question, Wordpress uses a "cron lock" defined('DOING_CRON') and sets a transient $lock = get_transient('doing_cron') when the spawn_cron method is invoked.
So, if you have a look at wp-includes/cron.php you'll see Wordpress crons do not run concurrently by default and will not run more than once every 60 seconds.
// don't run if another process is currently running it or more than once every 60 sec.
if ( $lock + WP_CRON_LOCK_TIMEOUT > $gmt_time )
return;
If you can only send one or two emails at a time this is going to be tricky to solve. An easier way to solve this would probably be to have WordPress use an SMTP email server that allows the frequency of emails you need to send. Just adding a new email account on your current hosting provider might suffice. If you do not know how to set that up manually there are plugins that will do that for you.
As php runs from top to bottom so when you schedule a event using wordpress schedule event function, as below :
if (! wp_next_scheduled ( 'my_hourly_event' )) {
wp_schedule_event(time(), 'hourly', 'my_hourly_event');
}
add_action('my_hourly_event', 'do_this_hourly');
function do_this_hourly() {
// do something every hour
}
This function do_this_hourly() will run as per the schedule , but the code which you will write inside that function will run one by one only.
Let us take example of email sending to 5 persons, so the email will be sent to them one by one in a loop.
The time-stamp is entered by the insert query which you are using, there is no connection between the timestamp and the mail sent time, this timestamp you have created for your own logs , so that you can check.
There would be some difference for sure i:e 10 seconds, it can also be less or greater, depending on the time which server is taking to send email and process the insert query.
Each query will be fired and the timestamp will be inserted according to the time at that moment (server time).

need to send SMS and EMail to group of user if record's status is not changed aftewr 24 hrs?

I am using php and Mysql.
I have a record in my database and i want to check status value of the record after 24hrs of its insertion if it is still in pending or no changed i want to send an SMS and an Email to some person relevant to the status.
To achieve this i have implemented a solution in which i used a php code but it need to continuously execute and check status of record that may cause DoS.
In Another solution i create a trigger but i can't able to send db values as parameter to the php file.
so what should be its solution????
Two ways came into my mind for this.
First, (the good way) using cronjob. It's a really good way.
Second, (bad way for your purpose) Check to see which rows has age of 30 days in each request coming to website. There are cons for this way as the website doesn't get visitors for some days then SMS or Emails won't be sent on time. Another bad thing is it executes on every request so loading time and memory will be consumed during this process.
created a php file which contains a functionality of send sms and email.
then create cronjob:
wget http://example.com/x.php
provide full address of your file.
while creating cronjob set time interval 24hrs

run a task or code automatically every day

I hope to limit the number of messages sent for users of my site develloped in sf 1.4, so the idea is to count for every user the number of messages sent for every day,so if a user exceed 10 messages for example then he can't send another message for this day he must wait until tomorrow.
I'm thinking to create a task and run it every day at midnight and put all number of messages for every user to 0, so my questions are :
Do you think it's a good idea to realize it?
Can someone now how to do to run a task or a code every 24 hours in symfony?
edit
Ok I have a cpanl on my server give me any tutorials to setup a cron job or sample code of Task,I don't have any idea?
A cron Job would solve the problem.
The cron jobs helps you to run codes automaticallly on the server, go through the link

Categories