使用 php 脚本安装 cron 作业

2022-01-03 00:00:00 cron php

我正在开发一个需要使用 Cron 的 Web 应用程序.我想通过像 Wordpress 这样的自动安装过程来简化设置.在设置 Cron 之前,我一直在编写安装脚本没有问题.请告诉我是否可以这样做.

I'm developing a web application that requires the use of Cron. I'd like to make it easy to setup with an auto install process like Wordpress. I have no problems writing the install script up en till its time to set up Cron. Please tell me if I can do this.

推荐答案

您只需要创建 cron 文件,然后使用 exec 设置该 cron:

You just have to create the cron file, then use exec to set up that cron:

$cron_file = 'cron_filename';
// Create the file
touch($cron_file); 
// Make it writable
chmod($cron_file, 0777); 
// Save the cron
file_put_contents($cron_file, '* * * * * your_command'); 
// Install the cron
exec('crontab cron_file');

这就要求运行 PHP 的用户有创建 crontab 的权限.默认情况下,此 cron 文件将替换该用户的任何其他 cron,因此请务必询问用户是否要应用该 cron.还要确保您正在写入 crontab 文件的文件夹是可写的.

This requires that the user which PHP is run under has the right to make crontabs. This cron file will by default replace any other crons for that user, so make sure to ask the user if he wants to apply the cron. Also make sure the folder you're writing the crontab file in is writable.

相关文章