pcrumm/crony

基于PHP的cron管理器

dev-master 2015-10-04 23:57 UTC

This package is not auto-updated.

Last update: 2024-09-28 17:49:20 UTC


README

Crony 是一个基于PHP的cron作业框架。将主任务添加到您的crontab,然后 Crony 将负责所有必要的工作,以确保您的离线作业按您希望的方式运行,在您希望的时间运行。

安装

  1. 安装 composer.

  2. Jobby 添加到 composer.json.

    "pcrumm/crony": "dev-master"

  3. 运行 composer install

  4. 将以下内容添加到您的crontab中(以下为示例 jobs.php

    * * * * * cd /path/to/project && php jobs.php 1>> /dev/null 2>&1

用法

jobs.php

jobs.php 加载并运行Crony任务,应从crontab引用。它应该包含对 Crony::init() 方法的调用,该方法接受一个参数:您的任务所在的命名空间。此命名空间应由 PSR-0 自动加载由composer,并且按照惯例应位于项目根目录下的 src 目录中。以下示例中,所有任务都是 src/PhilCrumm/ExampleTasks 目录的子目录,因此位于 \PhilCrumm\ExampleTasks 命名空间中。

<?php
/**
 * This is an example jobs.php file, which will initialize Crony and provide
 * the configuration information necessary to run your tasks.
 */
require( __DIR__ . '/vendor/autoload.php' );

$crony = \Crony\Crony::init( '\PhilCrumm\ExampleTasks', __DIR__ . '/src' )->run();
?>

示例任务

通常,Crony任务将存在于指定的命名空间中,并包含一个实现 \Crony\TaskInterface 接口的单个PHP文件(文件名与其类名匹配)。它将至少包含两个函数:返回Jobby格式配置数组的 config(),以及在cron任务运行时将运行的 run()

src/PhilCrumm/ExampleTasks/SayHello.php

<?php
namespace PhilCrumm\ExampleTasks;

class SayHello implements \Crony\TaskInterface {
    /**
     * Crony supports all of Jobby's configuration settings.
     * @see https://github.com/hellogerard/jobby
     * 
     * At minimum, we'll need enabled (a boolean), which determines whether
     * the job can run, and schedule, a cron-formatted string for when to run a job.
     */
    public static function config() {
        return array(
            'enabled'   => true,
            // Run every five minutes
            'schedule'  => '*/5 * * * *',
        );
    }

    /**
     * This function will be ran every time the above schedule is met.
     * We're just printing a string to the standard output (which will be
     * discarded per the crontab line earlier in the readme), but generally
     * you'd do something a little heftier.
     */
    public static function run() {
        print 'Hello, world!';
        return true;
    }
}
?>

特性

Crony 是围绕 Jobby 的包装,并提供了Jobby的所有功能。

特别是,Crony 对于cron作业提出了一种约定(而不是配置)。

致谢

Crony 是基于 Gerard Sychay 的出色工具 Jobby 构建的。