1. Go to this page and download the library: Download zhengqi/swoole-crontab library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
zhengqi / swoole-crontab example snippets
namespace app\scheduler;
use crontab\SchedulerInterface;
/**
* 定时任务心跳检测
*/
class SchedulerHeartbeat implements SchedulerInterface
{
/**
* crontab 日期表达式。如果不想存在其他地方,可以直接写在这里
*/
private string $defaultCrontabRule = "*/5 * * * * *";
public function run(): void
{
echo 'scheduler heartbeat running. date = ' . date('Y-m-d H:i:s') . PHP_EOL;
}
public function getCronRule(): string
{
return $this->defaultCrontabRule;
}
}
// 启动
$schedulerHelper = new SchedulerHelper();
$schedulerHelper->run();
// 写了个助手类,参考下
// ThinkPHP框架中,可以使用 app()->log
namespace crontab;
class SchedulerHelper
{
private Scheduler $scheduler;
private SchedulerRegistrar $schedulerRegistrar;
private array $schedulers = [];
public function __construct()
{
$this->schedulerRegistrar = new SchedulerRegistrar(app()->log);
$this->schedulers = []; // 获取你的任务列表
}
public function run($daemon = false): void
{
$this->addTasks();
$this->scheduler = new Scheduler($this->schedulerRegistrar, app()->log);
$this->scheduler->start($daemon);
}
private function addTasks(): void
{
foreach ($this->schedulers as $taskName => $taskClass) {
if (class_exists($taskClass)) {
echo 'class exists: ' . $taskClass . PHP_EOL;
$task = new $taskClass();
$this->schedulerRegistrar->addTask($task, $taskName);
}
}
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.