我应该如何在PHP中创建一次性计划任务?克龙?

时间:2011-09-12 19:46:37

标签: php cron scheduled-tasks

我正在创建一个Web应用程序,用户可以在其中指定运行2个计划任务的时间和日期(一个在开始日期,一个在结束日期)。由于这些只运行一次,我不知道一个cron工作是否合适。

我想到的另一个选择是将所有任务时间保存到数据库并每小时运行一次cron作业以检查是否$usertime == NOW()等。但我担心工作重叠等等。 / p>

思想?

附加:许多用户可以创建许多任务,每个任务运行2个脚本。

3 个答案:

答案 0 :(得分:1)

我会这样做,保存数据库中的设置,并在需要时检查任务是否应该开始。

你可以每分钟运行一次检查/启动cronjob。只需确保检查代码不会太重(快速退​​出)。对于几行的数据库查询应该不是每分钟都要执行的问题。

如果“任务”真的很重,你应该考虑一个守护进程而不是一个调用php的cronjob。这是一个很好的&易于阅读的介绍:Create daemons in PHP


编辑:我理所当然地认为即使任务只是“每次”运行一次,你也有多个用户以1:1的比例运行“每次一次”,从而为每个用户提供工作。如果没有,at(正如评论所说)看起来值得进行实验。

答案 1 :(得分:1)

无论你选择什么机制(cron / at / daemon),我都只会将启动任务放入队列中。与启动任务一起是放置结束任务。那部分可以将它置于未来或者它已经过去的时间立即启动它。这样他们永远不会重叠。

我也赞成PHP / DB和cron选项。看起来更简单,更灵活 - 如果性能决定,可以选择多个线程等。

答案 2 :(得分:1)

cron非常适合定期运行的脚本,但是如果你想在特定时间运行一次性(或两次)脚本,你可以使用unix'at'命令,你可以这样做直接从php使用这样的代码:

/****
 * Schedule a command using the AT command
 *
 * To do this you need to ensure that the www-data user is allowed to
 * use the 'at' command - check this in /etc/at.deny
 *
 *
 * EXAMPLE USAGE ::
 *
 * scriptat( '/usr/bin/command-to-execute', 'time-to-run');
 * The time-to-run shoud be in this format: strftime("%Y%m%d%H%M", $unixtime)
 *
 **/

function scriptat( $cmd = null, $time = null ) {
    // Both parameters are required
    if (!$cmd) {
        error_log("******* ScriptAt: cmd not specified");
        return false;
    }
    if (!$time) {
        error_log("******* ScriptAt: time not specified");
        return false;
    }

    // We need to locate php (executable)
    if (!file_exists("/usr/bin/php")) {
        error_log("~ ScriptAt: Could not locate /usr/bin/php");
        return false;
    }

    $fullcmd = "/usr/bin/php -f $cmd";

    $r = popen("/usr/bin/at $time", "w");
    if (!$r) {
        error_log("~ ScriptAt: unable to open pipe for AT command");
        return false;
    }
    fwrite($r, $fullcmd);
    pclose($r);

    error_log("~ ScriptAt: cmd=${cmd} time=${time}");

    return true;
}