开发者

How to set up a cron job via PHP (not CPanel)?

How to set up a cron开发者_开发知识库 job via PHP (not CPanel)?


Most Linux systems with crond installed provides a few directories you can set up jobs with:

/etc/cron.d/
/etc/cron.daily/
/etc/cron.weekly/
/etc/cron.monthly/
...

The idea here is to create a file in one of these directories. You will need to set the proper permissions/ownership to those (or one of those) directories so that the user launching the PHP script can write to it (Apache user if it's a web script, or whatever CLI user if CLI is used).

The easiest thing is to create an empty file, assign proper permission/ownership to it, and have the PHP script append/modify it.

Per example:

$ touch /etc/cron.d/php-crons
$ chown www-data /etc/cron.d/php-crons

Then in PHP:

$fp = fopen('/etc/cron.d/php-crons', 'a');
fwrite($fp, '* 23 * * * echo foobar'.PHP_EOL);
fclose($fp);


If what you're getting at is dynamically adding lots of jobs to crontab form your application, a better way to do that is manually add ONE cron job:

php -f /path/to/your/runner.php

Store your jobs that you would be adding to cron manually in a table (or one table per task-type), and then have your runner go through the table(s) every minute/hour/day/whatever and execute all the ones that should be executed at that time.


From pure PHP I will create deamon that will manage this (those) cron job(s).

how to create it: http://kevin.vanzonneveld.net/techblog/article/create_daemons_in_php/ to start with


Finding crontab file isn't easy on shared hosting and there's no certainty that cron will read that file again while it's already running. Actually I the best way is to use corntab command.

If you don't have access to shell you can use for example PHPShell. Try this.

  • Uplode a txt file via FTP with jobs in crontab fomat for example

    5 * * * * /some/file/to/run.sh > /dev/null

(remember to put a newline at the end of that line)

  • Log in to your PHPShell and run

    crontab uploded_filename.txt

  • Remember to change file permissions

    chmod 775 uploded_filename.txt

  • Check your cron jobs using

    crontab -l

Cheers


There is an embargo on the use of PHP to edit crontabs which has been in place since 2004. You may not be allowed to do this if you live outside of the United States, check with your local government agency.

But seriously, you could always call "crontab -" with a system call. If you need to do this for some user other than the webserver, you'll need some ssh or sudo magic. But it all seems like a bad idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜