ivva
ivva

Reputation: 2949

How to run cron job in php

I have php function that I wnat to run every 15 minutes. I found some questions like this:

How can I make a cron to execute a php script?

and in my case I should use this:

*/15 * * * * /usr/local/bin/php -q /path/to/my/file.p

But should I run this command in terminal or put it in my file? And once, it is executed, will it run all the time or will have time limit?

Thanks!

Upvotes: 1

Views: 32668

Answers (2)

lhermann
lhermann

Reputation: 490

PHP doesn't run cron jobs, your server (or operating system) is doing this. There are two ways to put your cron job to work:

#1

Using the shell command crontab. The command crontab -l will list all existing cronjobs for your user (most likely there are none yet). crontab -e will open an editor window where you can put in a you cron job as a new line. Save, and your cron job is now running. crontab -l again and you will see it listet. crontab -r to remove all the cont jobs.

You can also start a cron job from a file. Simply type crontab filename (eg. crontab textfile.txt)

Alternatively you can also start it from within PHP. Just put your cron job into a file and start it via exec() like so:

file_put_contents( 'textfile.txt', '*/15 * * * * /usr/local/bin/php -q /path/to/my/file.php' );
exec( 'crontab textfile.txt' );

#2

If you have admin privileged on your system you can create a file in /etc/cron.d/ (for example, call it my_cronjob) and put your cron job there. In this case you probably want to run it as a user (not as admin, that would be rather insecure). This is quite easy to do, just add the user name like so:

*/15 * * * * user_name /usr/local/bin/php -q /path/to/my/file.p

(In this case the cron job will not be listet under crontab -l)


Answering your second question: As long as the cron job is listet in crontab -l or as long as the file is sitting in /etc/cron.d the cron job is running, in your case, every 15 minutes.

Upvotes: 6

Desert_king
Desert_king

Reputation: 96

10 * * * * /usr/bin/php /www/virtual/username/cron.php > /dev/null 2>&1 There are two main parts:

The first part is "10 * * * *". This is where we schedule the timer. The rest of the line is the command as it would run from the command line. The command itself in this example has three parts:

"/usr/bin/php". PHP scripts usually are not executable by themselves. Therefore we need to run it through the PHP parser. "/www/virtual/username/cron.php". This is just the path to the script. "> /dev/null 2>&1". This part is handling the output of the script. More on this later.

Please read this tutorial http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800

Upvotes: 2

Related Questions