Task/Job scheduling on PHP - php

Our system based on Zend 1 has a background process running as daemon to check hourly whether user has expired or not, if yes, the system will send verification email to these expired users.
The code is really simple:
while(1) {
$worker = ... //get verification worker
$worker->run();
sleep(3600); //run hourly
}
We would like to look for better approach with free tool to replace this code to schedule job in the system. Zend Job Queue is really good approach but it is commercial.
My thinking on two below approaches as Zend Job Queue alternative:
Instead of running daemon, configure cron jobs on crontab to run PHP script hourly, but I am not sure whether it is better on above code or not.
Run node cron on nodejs server to call PHP script directly.
I also have looked on Gearman and beanstalked whether they supports on job scheduling but really stumped on this way.
Please suggest if there is any better approach to schedule task on PHP.

Cron would definately be the preferred way to automate tasks, and not a php script in an infinite loop.
see : http://en.wikipedia.org/wiki/Cron
You many also want to consider using Zend Server which includes a component called Zend Job Queue which provides offline asynchronous processing of tasks and activities.
see : http://files.zend.com/help/Zend-Server-6/content/jobs_component.htm
see : http://www.zend.com/en/products/server

0 * * * * /usr/bin/php -q /yourpath/verification_worker.php
you can use crontab to run this task every hour
Hope this helps

Related

Excute script for n minutes in a user defined range of time

I want to execute a php or python script on a server with values from a database for n minutes a day in a user defined range of time which I would like to store in a database too. So my question is: How can I achive this the most performant and scalable way?
So a user should set a range of time in which the script should be executed, I couldn't figure out how i could do this if multiple users selected the same range of time.
Thanks for your ideas.
Check out cron and gearman.
Both are services that run on linux and would be able to execute either PHP or Python scripts in a predictable and scalable way.
The basic structure of your mechanism would be...
Job initiator - this script would be invoked automatically by cron (every minute max). It would execute very quickly and then exit. You would use this to check the DB for jobs that should be started during that minute, and pass them off to Gearman.
Job executor - this script executes a single job. Since Gearman handles concurrency for you, you only have to worry about doing a single long-running process here.
You can easily configure Gearman to handle many concurrent jobs. Also, there are good Gearman packages for both Python and PHP (I've used them both with great success).
Here is some pseudocode to help you understand how this would work:
initiate.php
<?php
$gearmanClient= new GearmanClient();
$gearmanClient->addServer();
$workloads = fetchWorkloads(time());
foreach ($workloads as $workload) {
$gearmanClient->doBackground('execute', json_encode($workload));
}
execute.php
<?php
$gearmanWorker = new GearmanWorker();
$gearmanWorker->addServer();
$gearmanWorker->addFunction('execute', 'executeMethod');
while($gearmanWorker->work()) {
// Handle any errors here
}
function executeMethod($job)
{
$workload = json_decode($job->workload());
while (time() < $workload->stopTime) {
// Do your task for an amount of time here
}
}
Again, this is just pseudocode. You will need to flesh it out based on your requirements. Obviously you'll also need to learn, install, and/or configure cron and Gearman.
Your cron entry might look like this:
* * * * * www-data php /var/www/my-app/initiate.php
For Gearman, I would recommend using supervisor to ensure that your workers are restarted, etc when they inevitably encounter problems. Your supervisor config might look like this:
[program:myProgram]
user=www-data
command=php /var/www/my-app/initiate.php
numprocs=1
stdout_logfile=/var/log/supervisord.log
autostart=true
autorestart=true
stopsignal=KILL

Background php task, cron alternatives

I have some background tasks in my php-project. It shoud do some job if some condition satisfied. For example: if there are some orders than not yet delivered and time left to estimate delivery is less than 15 minutes, system sends notification to courier that he's probably late.
The simpliest solution - create cron task that runs php script every minute. That script will check that condition and send notification if condition is fulfilled.
Another approach is queues. I looked at gearman and rabbitmq, but as i can see they a for another usecase. They fit if you have some client that directly sends tasks. In my case i don't have any client, its just some condition in system.
And the last solution i figured is write custom php-daemon with infinite loop. In each iteration it check condition, do the job if its satisfied and sleeps for 1 minute. But there are possible problems with memory leaks, daemon restarting, etc.
So, what the best solution to this promlem in modern php?
If you do not like to use cronjob I guess your best option is to write a daemon. I like coding in Perl and if I were you I would write a daemon in Perl.
However, If I were to write the daemon in PHP, I would run another backup script in cronjob (10 min interval for example) that will check if my php daemon is running or not and restart the daemon if not running.
If cron can do the job for you, then by all means use it. Why reinvent the wheel when there is a proven tool that does the job? I wrote some
while (1) {
// run forever scripts
}
and they ran months without errors; they processed message queues which were simple mysql tables. But if you do that, you will need a cron job that checks for the while (1) process state, you will need some locking to prevent the process being started multiple times, etc. Just go with cron.
I would make a small nodejs app for this or laravel queues:
https://laravel.com/docs/5.3/queues
It's up to you.

How to assign cron jobs through php

Is it possible to schedule some tasks in php to run automatically on the server at a certain time of the day? . I heard abt cron jobs. is there any way to set it via php code
http://php.net/system lets you to run any command-line utility.
As for the certain command to set a cron job you have either to google a little or ask on serverfault.

Timed scripting PHP

I am trying to figure out how to do time scripting in PHP. Basically let's say in my application, I want to do a task at timed intervals (e.g., send email notification to users everyday, do some database cleanup at certain times, etc.) How is this type of scripting (scheduling) is done in PHP? If not possible in PHP, then how to do it and in what language? I am both Linux and Windows sharing hosting accounts, so I would like this method if possible to be universal.
Any help is appreciated.
I just schedule cron jobs that run PHP scripts.
*/5 * * * * php /var/www/cron/cleanup-db.php
An alternate (Windows-compatible) approach would be to run a persistent PHP script which sleeps for an interval, and on wakeup it checks to see if any jobs need to be run. For example, check to see if any pending requests have not had a response or a reminder email in N hours.
On Unix machines, you use cron, which is for re-occuring jobs. On Windows, the equivalent is at
Cron is the obvious choice but you may not be able to use it because you host your site on a "shared" environment. Try online services that generate auto http requests to your URLs based on the schedule you set. Google "schedule http request online", there are many of such services out there, some of them are free or have free options.
To complete Adam's answer, in Windows you have the chance to make Scheduled Tasks, wich can be programed to given intervals. That's the way we do.
The problem I see is that you are talking about shared hostings, probably you don't have rights to schedule task in that environment. In that case you should ask your system admin if such task is available.
There is another requirement: the task can be made in php if you have php-cli available, so check it out too.
You are looking for cron job
http://en.wikipedia.org/wiki/Cron

What options are there for executing a PHP script at a certain time every day?

I have a PHP script that needs to be run at certain times every weekday. Is cron or Windows task scheduler the only way to do this?
Is there a way to set this up from within another PHP script?
Depends how exact the timing needs to be. A technique I've seen used (dubbed "poor man's cron") is to have a frequently accessed script (a site's home page, for example) fire off a task on the first page load after a certain time (kept track of in the database).
If you need any sort of guaranteed accuracy, though, cron or a Windows scheduled task is really the best option. If your host doesn't support them, it's time to get a better one.
Apart from cron or Scheduled Tasks, you can have your PHP script to always run it. The process should sleep (within a loop) until the time has reached. Then, the process could execute the remaining functions/methods. Or, you can set up another script (which will act as a daemon) to check for the time and execute the other script.
Well since the web is a pull mechanism you have to have some sort of action that will trigger a PHP script to execute. cron is an option on *nix and task scheduler on windows. You could also write your own service that has a timer but only if needed, this is common on windows services for updaters, jobs etc.
One way you could do it is in the cron task just call a php script for each action needed. Or one php script that executes other tasks. The problem with web based tasks though such as PHP is timeouts. Make sure your tasks are under 60-90 seconds. If not you might look at using python , perl or ruby or even bash scripts to do the work rather than the PHP script.
cron seems like the best option for you though. You will have to call your script with wget. There are examples here: http://www.thesitewizard.com/general/set-cron-job.shtml
For instance this runs the script everyday at 11:
30 11 * * * /usr/bin/wget http://www.example.com/cron.php
Cron, of course, is by far the best way to schedule anything on *nix.
If this is in a remote server you do not have cron access to, you can setup cron/windows scheduler on your computer, to open a web browser to the page that contains the script you wish to run
You probably want to use cron (or windows scheduled tasks).
If you really wanted, you could set up another php script to run continuously with an infinite loop (with a sleep command inside the loop, say for 30 seconds or so) and then when you reach your desired day/time execute the other script via a shell command call. While possible, I can't think if a single good reason to use this method rather than cron/scheduled tasks
You can write a long running script that runs your main script in predefined times but it will be very unnecessary, error prone, and it will basically be a "cron rewrite in phph".
Using the real cron itself will be easier and a more robust solution. If you are packaging an application, you can put a file in /etc/cron.d which contains a single cron line running your application.
You'll need to use a cron job (under Linux/Unix) or a scheduled task under Windows. You could have another script running on a continuous basis which checks the time and executes a script at a specified interval, but using the OS-supplied mechanism is easier to manage and resilient to restarts, etc.
The Uniform Server project has some good suggestions on mimicking cron in environments where cron is unacceptable. Still though, if cron is at all an option, use it.

Categories