php 实现简单的自定义计划任务组件 crontab-jobs

2021年12月4日10:22:18

 

gitee包地址:https://gitee.com/open-php/crontab-jobs

两个包总共才几个文件,性能消耗小,包小,特别适合做一些服务组件

 

支持composer

composer require zx/crontab-jobs dev-master

 

crontab-jobs
介绍
PHP定时任务组件

后续需要新增的功能
1,支持日志功能
2,支持任务重试功能
3,支持任务互斥锁

使用
use Zx\CrontabJobs\Command;
use Zx\CrontabJobs\Kernel;
use Cron\CronExpression;

ini_set('date.timezone', 'Asia/Shanghai');

class t1 extends Command
{
    private string $contab;
    private string $retry;

    public function __construct(string $contab = '', int $retry = 0)
    {
        $this->contab = $contab;
        $this->retry = $retry;
    }

    public function handle()
    {
        print_r(self::class);
        echo PHP_EOL;
        print_r(date('Y-m-d H:i:s'));
        echo PHP_EOL;
    }

    public function getRetry()
    {
        return $this->retry;
    }

    public function getCrontab()
    {
        return $this->contab;
    }
}

class t2 extends Command
{
    private string $contab;
    private string $retry;

    public function __construct(string $contab = '', int $retry = 0)
    {
        $this->contab = $contab;
        $this->retry = $retry;
    }

    public function handle()
    {
        print_r(self::class);
        echo PHP_EOL;
        print_r(date('Y-m-d H:i:s'));
        echo PHP_EOL;
    }

    public function getRetry()
    {
        return $this->retry;
    }


    public function getCrontab()
    {
        return $this->contab;
    }
}

$t1 = new t1('* * * * *', 0);
$t2 = new t2('*/5 * * * *', 0);

Kernel::register($t1);
Kernel::register($t2);

Kernel::run('now', new DateTimeZone('Asia/Shanghai'));
业务脚本继承Command之后,就可以直接注册到Kernel 然后直接调用

Kernel::run('now', new DateTimeZone('Asia/Shanghai'));
支持时区切换

添加计划任务
* * * * * cd /data/code/crontab-jobs/tests && /usr/local/php80/bin/php /data/code/crontab-jobs/tests/test.php >> /data/crontab.log
指定特定用户执行
* * * * * sudo -u www && cd /data/code/crontab-jobs/tests && /usr/local/php80/bin/php /data/code/crontab-jobs/tests/test.php >> /data/crontab.log

 

 

 

 

 

 

posted on 2021-12-04 12:16  zh7314  阅读(266)  评论(0编辑  收藏  举报