webman: 实现crontab定时任务功能

一,安装第三方库:

文档地址:

https://www.workerman.net/doc/webman/components/crontab.html

从命令行安装:

$ composer require 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.7)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Downloading workerman/crontab (v1.0.7)
  - Installing workerman/crontab (v1.0.7): Extracting archive
> support\Plugin::install
Generating autoload files
26 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
Found 1 security vulnerability advisory affecting 1 package.
Run "composer audit" for a full list of advisories.
Using version ^1.0 for workerman/crontab

安装完成后查看版本:

$ composer show workerman/crontab
name     : workerman/crontab
descrip. : A crontab written in PHP based on workerman
keywords : crontab
versions : * v1.0.7
released : 2025-01-15, 5 months ago
type     : library

时间说明:

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位,则最小时间粒度是分钟]

二,代码

1,创建task

<?php
namespace app\process;

use Workerman\Crontab\Crontab;

class Task
{
    public function onWorkerStart()
    {

        // 每分钟执行一次
        new Crontab('0 */1 * * * *', function(){
            echo date('Y-m-d H:i:s')."\n";
            $this->checkNowDate();
        });
    }
    
    //检查当前时间
    private function checkNowDate() {
        $dateStr = "当前时间:".date('Y-m-d H:i:s')."\n";
        error_log($dateStr,3,'/data/logs/businesslogs/task.log');
        echo date('Y-m-d H:i:s')."\n";
    }
}

2,配置task启动

在config/process.php中附加:

    'task'  => [
        'handler'  => app\process\Task::class
    ],

三,测试效果:

写到日志文件中的数据

当前时间:2025-07-07 14:19:00
当前时间:2025-07-07 14:20:00
当前时间:2025-07-07 14:21:00

 

posted @ 2025-07-19 07:46  刘宏缔的架构森林  阅读(45)  评论(0)    收藏  举报