gpt4 book ai didi

站点管理员配置的 PHP 任务计划程序

转载 作者:行者123 更新时间:2023-11-29 01:36:55 25 4
gpt4 key购买 nike

我正在尝试为我的站点上的管理员创建一种方法来安排任务,类似于我在服务器上设置 cron 作业以运行特定脚本的方式。我希望他们对任务运行的时间有类似的控制,例如每天中午 14:00 或每周四中午 12:00 等。

我想我会有一个表格,询问他们希望多久运行一次任务,在哪几天/几周等。然后将其存储在数据库中。接下来,我将创建一个 cron 作业来每分钟运行一个脚本。然后该脚本将选择数据库中应运行的所有任务并执行每个任务。

为此,我一直在研究任务调度器,到目前为止,它们中的大多数似乎都是为 Web 开发人员构建的,以便以编程方式调度任务。相反,我想将它们存储在数据库中,然后编写一个 SQL 查询来选择要运行的正确任务。我想知道应该使用什么结构将计划存储在数据库中,以及如何检索在特定时间运行的正确任务?

如果有人能指出正确的方向,我将不胜感激。

最佳答案

这里是一个简化的解释和示例,说明我是如何在过去的项目中看到这个实现的。为简洁起见,我省略了安全方面的考虑,但请注意,让用户指定要运行的命令本质上是不安全的。

任务 SQL 表

您需要设置这三列供您的执行脚本使用。间隔列是一个 cron 字符串(分钟小时日月年)。 script_path 列是脚本运行的路径。 last_executed 列是上次运行该任务的时间。 interval 和 last_executed 列将用于确定是否应执行任务。

+----+------------+----------------------+---------------------+
| id | interval | script_path | last_executed |
+----+------------+----------------------+---------------------+
| 1 | 5 * * * * | /path/to/script1.php | 2016-01-01 00:00:00 |
+----+------------+----------------------+---------------------+
| 2 | * 12 * * * | /path/to/script2.php | 2016-01-01 00:00:00 |
+----+------------+----------------------+---------------------+

任务执行脚本

此脚本将通过 cron 作业每分钟运行一次。

#/usr/bin/env php
<?php

// Get tasks from the database
$db = new PDO('dsn', 'username', 'password');
$stmt = $db->prepare('SELECT * FROM `tasks`');
$stmt->execute();
$tasks = $stmt->fetchAll(PDO::FETCH_OBJ);

foreach ($tasks as $task) {
$timestamp = time();
$lastExecutedTimestamp = strtotime($task->last_executed);
// Convert cron expression to timestamp
$intervalTimestamp = $task->interval;

// Check if the task should be run.
if ($timestamp - $lastExecutedTimestamp >= $intervalTimestamp) {
// Execute task
// ...

// Update the task's last_executed time.
$stmt = $db->prepare('UPDATE `tasks` SET `last_executed` = ? WHERE `id` = ?');
$stmt->execute([date('Y-m-d H:i:s', $timestamp), $task->id]);
}
}

关于站点管理员配置的 PHP 任务计划程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39728926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com