Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set cron job through PHP script

Tags:

php

cron

How can I set cron job through PHP script.

like image 232
Simpanoz Avatar asked Feb 27 '11 18:02

Simpanoz


People also ask

Do you know how do you setup cron jobs for php website?

Timing – set the weekday, months, days, hours and minutes. Execute – the cron job needs to be called in PHP to run – that's located at /usr/bin/php path. Script Path – the path of the file you want to run. Output – you are allowed to add the cron output to a file or discard it. /dev/null 2>&1 will discard.


2 Answers

This will add a script that runs every day at 9:30am.

exec('echo -e "`crontab -l`\n30 9 * * * /path/to/script" | crontab -');

You may run into problems with permissions if you are running this script from a web server. To get around this, I would suggest a different approach.

Here is one possible solution. Create a list of scripts that need to be run. You can save this in a text file or in a database. Create a script to read this list and run it every minute or every 5 minutes (using a cronjob). Your script will need to be smart enough to decide when to run the list of scripts and when to simply exit.

like image 192
Nick Clark Avatar answered Oct 12 '22 02:10

Nick Clark


Do you know how to set a cron job normally? (outside of PHP, i.e. from a bash script or the command line).

If so, you just need to use the php function exec to issue the same commands you would have to create the cron job at the command line. One caveat is that there may be permission issues and you have to be really careful about what you put in that exec function (you don't want to pass input from the end user to that function).

like image 36
Matt Bridges Avatar answered Oct 12 '22 01:10

Matt Bridges