您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
workerman-crontab定时任务
发布时间:2021-12-31 21:53:26编辑:雪饮阅读()
workerman/crontab
说明
workerman/crontab 是一个基于workerman的定时任务程序,类似linux的crontab。workerman/crontab支持秒级别定时。
使用 workerman/crontab需要先设置好php的时区,否则运行结果可能和预期的不一致。
时间说明
0 1 2 3 4 5
| | | | | |
| | | | | +------ day of week (0 - 6) (Sunday=0)
| | | | +------ month (1 - 12)
| | | +-------- day of month (1 - 31)
| | +---------- hour (0 - 23)
| +------------ min (0 - 59)
+-------------- sec (0-59)[可省略,如果没有0位,则最小时间粒度是分钟]
注意:定时任务不会马上执行,所有定时任务进入下一分钟才会开始计时执行。
安装
[root@localhost workerman]# composer require workerman/crontab
Using version ^1.0 for workerman/crontab
./composer.json has been updated
Running composer update workerman/crontab
Loading composer repositories with package information
Updating dependencies
Lock file operations: 1 install, 0 updates, 0 removals
- Locking workerman/crontab (v1.0.2)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
- Downloading workerman/crontab (v1.0.2)
- Installing workerman/crontab (v1.0.2): Extracting archive
Generating autoload files
2 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
实例:
<?php
use Workerman\Worker;
require __DIR__ . '/vendor/autoload.php';
use Workerman\Crontab\Crontab;
$worker = new Worker();
// 设置时区,避免运行结果与预期不一致
date_default_timezone_set('PRC');
$worker->onWorkerStart = function () {
// 每分钟的第1秒执行.
new Crontab('1 * * * * *', function(){
echo date('Y-m-d H:i:s')."\n";
});
// 每天的7点50执行,注意这里省略了秒位.
new Crontab('50 7 * * *', function(){
echo date('Y-m-d H:i:s')."\n";
});
};
Worker::runAll();
实例运行一小会儿后:
[root@localhost workerman]# php index.php start
Workerman[index.php] start in DEBUG mode
------------------------------------- WORKERMAN --------------------------------------
Workerman version:4.0.26 PHP version:7.3.31
-------------------------------------- WORKERS ---------------------------------------
proto user worker listen processes status
tcp root none none 1 [OK]
--------------------------------------------------------------------------------------
Press Ctrl+C to stop. Start success.
2021-12-31 15:38:01
2021-12-31 15:39:01
关键字词:workerman,crontab,定时任务