How can I set cron job through PHP script.
-
My PHP script would run on Linux. – Simpanoz Feb 27 '11 at 18:27
-
1Are you asking about creating a cron job programatically in php? Or about creating a cron job that runs your php script? – Doug T. Feb 27 '11 at 18:32
3 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.

- 4,439
- 4
- 23
- 25
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).

- 8,168
- 9
- 66
- 99

- 48,277
- 7
- 47
- 61
You can't set a CRON job through PHP script, you have to set it one the server side. Unless you want to do it via system function, you can't set a CRON through php.
If you're not running on your own server and use hosting service, ask your hosting provider how to set up a CRON script (if the provider allows it).

- 14,832
- 10
- 62
- 88
-
@Marc B, yes but it's usually the server that takes care of the CRON scripts, not php _itself_. Maybe I didn't explain myself clear enough. – Czechnology Feb 27 '11 at 19:57