精华内容
参与话题
问答
  • cron

    2020-07-01 11:36:25
    Cron表达式详解 在线Cron表达式生成器 https://www.beejson.com/tool/cron.html https://crontab.guru/ a simple cross platform C library https://github.com/ssteidl/libhoro.git
    展开全文
  • Cron

    2018-01-16 17:26:23
    Installation ...Add "liebig/cron": "dev-master" to your /path/to/laravel/composer.json file at the "require": section (Find more about composer at http://getcomposer.org/)Run the compose

    Installation

    Laravel 5

    1. Add "liebig/cron": "dev-master" to your /path/to/laravel/composer.json file at the "require": section (Find more about composer at http://getcomposer.org/)
    2. Run the composer update liebig/cron --no-dev command in your shell from your /path/to/laravel/ directory
    3. Add 'Liebig\Cron\Laravel5ServiceProvider' to your 'providers' array in the /path/to/laravel/config/app.php file
    4. Migrate the database with running the command php artisan migrate --path=vendor/liebig/cron/src/migrations
    5. Publish the configuration file with running the command php artisan vendor:publish - now you find the Cron configuration file at /path/to/laravel/config/liebigCron.php and this file won't be overwritten at any update
    6. Now you can use Cron everywhere for free

    Laravel 4

    1. Add "liebig/cron": "dev-master" to your /path/to/laravel/composer.json file at the "require": section (Find more about composer at http://getcomposer.org/)
    2. Run the composer update liebig/cron --no-dev command in your shell from your /path/to/laravel/ directory
    3. Add 'Liebig\Cron\CronServiceProvider' to your 'providers' array in the /path/to/laravel/app/config/app.php file
    4. Migrate the database with running the command php artisan migrate --package="liebig/cron"
    5. Publish the configuration file with running the command php artisan config:publish liebig/cron - now you find the Cron configuration file at /path/to/laravel/app/config/packages/liebig/cron and this file won't be overwritten at any update
    6. Now you can use Cron everywhere for free

    Configuration

    Cron is designed to work out of the box without the need of configuration. To enable this a few default values are set. To change Cron's default settings there are two possibilities.

    Set methods

    You can use the Cron set methods (e.g. setDatabaseLogging, setRunInterval) to change Cron's behaviour. This changes are temporary and the set methods have to be called every time.

    Config file

    The behaviour values will be loaded from a config file. You can change this values easily by editing in Laravel 5 the /path/to/laravel/app/config/liebigCron.php file and in Laravel 4 the /path/to/laravel/app/config/packages/liebig/cron/config.php file. This is the more permanent way. If you only want to change settings for one run with conditions, we recommend to use the setter methods.

    NOTE: All values set via method will overwrite the values loaded from config file.


    Example

    Cron

    If you use Cron's integrated route or command, you only need to listen for the cron.collectJobs event. The best place to do this is in Laravel 5 the /path/to/laravel5/app/Providers/AppServiceProvider.php file at the boot method and in Laravel 4 the /path/to/laravel/app/start/global.php file.

    Laravel 5 - AppServiceProvider.php

    <?php namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    
    class AppServiceProvider extends ServiceProvider {
    
        //...
    
        /**
         * Bootstrap any application services.
         *
         * @return void
         */
        public function boot() {
            // Please note the different namespace
            // and please add a \ in front of your classes in the global namespace
            \Event::listen('cron.collectJobs', function() {
    
                \Cron::add('example1', '* * * * *', function() {
                    // Do some crazy things unsuccessfully every minute
                    return 'No';
                });
    
                \Cron::add('example2', '*/2 * * * *', function() {
                    // Do some crazy things successfully every two minute
                    return null;
                });
    
                \Cron::add('disabled job', '0 * * * *', function() {
                    // Do some crazy things successfully every hour
                }, false);
            });
        }
    }

    Laravel 4 - global.php

    Event::listen('cron.collectJobs', function() {
        Cron::add('example1', '* * * * *', function() {
                        // Do some crazy things unsuccessfully every minute
                        return 'No';
                    });
    
        Cron::add('example2', '*/2 * * * *', function() {
            // Do some crazy things successfully every two minute
            return null;
        });
    
        Cron::add('disabled job', '0 * * * *', function() {
            // Do some crazy things successfully every hour
        }, false);
    });

    Inside the anonymous function you can use all the Laravel and Cron functions. In the next step you have to configure the route or command which will start Cron.

    Using Cron's integrated route

    If you don't have shell access to your server, you can easily use an online cronjob service (Google knows some good provider). This provider will run Cron's route in a defined interval. The Cron route has to be protected because if someone else than the service provider invokes it, our jobs will be executed too often. For that reason we need a security key in addition to the route path. This key can be generated with the php artisan cron:keygen command call and has to be set in the Cron config file at the key cronKey.

        // Cron application key for securing the integrated Cron run route - if the value is empty, the route is disabled
        'cronKey' => '1PBgabAXdoLTy3JDyi0xRpTR2qNrkkQy'

    Now you have to configure the address and run interval at your online cronjob service provider. The address for the integrated Cron route is always http://yourdomain.com/cron.php?key=securitykey. For the above example this address could be http://exampledomain.com/cron.php?key=1PBgabAXdoLTy3JDyi0xRpTR2qNrkkQy and the run interval has to be every minute (due to the job with the name "example1"). Now the jobs were added, the route key was generated and the service provider was configured.

    Using Cron's integrated command

    If your hosting provider grants you shell access or you can manage cron jobs with a control panel software (e.g. cPanel or Plesk), the best way to run Cron is to use the integrated artisan cron:run command. For the above example the crontab or control panel software command could be * * * * * /usr/bin/php /var/www/laravel/artisan cron:run.

    NOTE: If you want to use Cron's in time check, which will test if the time between two Cron run method calls are correct, please configure the key runInterval. In our example we call the route every minute so the value should be 1.


    API

    Add a cron job

    Adding a cron job to Cron is very easy by using the static add function. As parameter the name of the cron job, the cron expression and an anonymous function is needed. The boolean isEnabled is optional and can enable or disable this cron job from execution (default is enabled).

    public static function add($name, $expression, $function, $isEnabled = true) {

    The name is needed for identifying a cron job if an error appears and for logging.

    The expression is a string of five or optional six subexpressions that describe details of the schedule. The syntax is based on the Linux cron daemon definition.

        *    *    *    *    *    *
        -    -    -    -    -    -
        |    |    |    |    |    |
        |    |    |    |    |    + year [optional]
        |    |    |    |    +----- day of week (0 - 7) (Sunday=0 or 7)
        |    |    |    +---------- month (1 - 12)
        |    |    +--------------- day of month (1 - 31)
        |    +-------------------- hour (0 - 23)
        +------------------------- min (0 - 59)
    

    The given anonymous function will be invoked if the expression details match with the current timestamp. This function should return null in the case of success or anything else if there was an error while executing this job. By default, the error case will be logged to the database and to a Monolog logger object (if logger is enabled).

    The isEnabled boolean parameter makes it possible to deactivate a job from execution without removing it completely. Later the job execution can be enabled very easily by giving a true boolean to the method. This parameter is optional and the default value is enabled.

    Example

    \Cron::add('example1', '* * * * *', function() {
                        // Do some crazy things successfully every minute
                        return null;
                    });
    \Cron::add('example2', '*/2 * * * *', function() {
                        // Oh no, this job has errors and runs every two minutes
                        return false;
                    }, true);

    Remove a cron job

    To remove a set cron job on runtime use the remove method with the cron job name as string parameter.

    public static function remove($name) {

    Example

    \Cron::add('example1', '* * * * *', function() {
                        // Do some crazy things successfully every minute
                        return null;
                    });
    \Cron::remove('example1');

    Enable or disable a cron job

    After adding an enabled or disabled cron job ($isEnabled boolean parameter of the add method call) you can disable or enable a cron job by name. For this use the setEnableJob or setDisableJob function.

    public static function setEnableJob($jobname, $enable = true) {
    public static function setDisableJob($jobname) {

    Example

    \Cron::add('example1', '* * * * *', function() {
                        // Do some crazy things successfully every minute
                        return null;
                    });
    \Cron::setDisableJob('example1');
    // No jobs will be called
    $report = \Cron::run();
    \Cron::setEnableJob('example1');
    // One job will be called
    $report = \Cron::run();

    Getter

    To receive the enable status boolean of a job, use the static isJobEnabled($jobname) method.


    Run the cron jobs

    Running the cron jobs is as easy as adding them. Just call the static run method and wait until each added cron job expression is checked. As soon as the time of the expression has come, the corresponding cron job will be invoked. That is the Cron magic. The run method returns a detailed report. By default Cron reckons that you call this method every minute (* * * * *) and by default the report (with their cron jobs errors) will be logged to database. You can change this interval using the setRunInterval function.

    public static function run() {

    Example

    $report = \Cron::run();

    NOTE: The run method call has to be the last function call after adding jobs, setting the interval, deactivating database logging and the other function calls.


    Set the run interval

    The run interval is the time between two cron job route calls. Some cron service provider only supports calls every 15 or even 30 minutes. In this case you have to set this value to 15 or 30. This value is only important to determine if the current run call is in time. If you have disabled database logging in general, you don't have to care about this.

    public static function setRunInterval($minutes) {

    NOTE: If the route call interval is not every minute you have to adjust your cron job expressions to fit to this interval.

    Example

    // Set the run intervall to 15 minutes
    \Cron::setRunInterval(15);
    // Or set the run intervall to 30 minutes
    \Cron::setRunInterval(30);

    Getter

    To recieve the current set run interval use the static getRunInterval() method.


    Enable or disable Laravel logging

    The Laravel logging facilities provide a layer on top of Monolog. By default, Laravel is configured to create daily log files for your application, and these files are stored in app/storage/logs. Cron will use Laravel logging facilities by default. You can disable this by setting the laravelLogging value to false in the config file or by calling the setLaravelLogging function at runtime.

    public static function setLaravelLogging($bool) {

    NOTE: You can add a custom Monolog logger to Cron and enable Laravel logging. In this case all messages will be logged to Laravel and to your custom Monolog logger object.

    Example

    // Laravel logging is enabled by default
    \Cron::run();
    // Disable Laravel logging
    \Cron::setLaravelLogging(false);
    // Laravel logging is disabled
    \Cron::run();

    Getter

    To recieve the enabled or disabled boolean value use the static isLaravelLogging() method.


    Set a Monolog logger

    If you want to add a custom Monolog logger object to Cron use the static setLogger method.

    public static function setLogger(\Monolog\Logger $logger = null) {

    NOTE: If you want to remove the logger, just call the setLogger method without parameters.

    Example

    \Cron::setLogger(new \Monolog\Logger('cronLogger'));
    // And remove the logger again
    \Cron::setLogger();

    Getter

    To recieve the set logger object use the static getLogger() method. If no logger object is set, null will be returned.


    Disable database logging

    By default database logging is enabled and after each cron run a manager object and job objects will be saved to database. We strongly recommend to keep the database logging activated because only with this option Cron can check if the current run is in time. It could make sense in some cases to deactivate the database logging with the setDatabaseLogging method.

    public static function setDatabaseLogging($bool) {

    Example

    \Cron::setDatabaseLogging(false);

    Getter

    To receive the current boolean value of the logging to database variable, just use the static isDatabaseLogging() function.


    Log only error jobs to database

    By default Cron will log all jobs to database. Maybe sometimes you want to log only error jobs (which not return null) to database by using the static setLogOnlyErrorJobsToDatabase function.

    public static function setLogOnlyErrorJobsToDatabase($bool) {

    Example

    // Log only error jobs to database
    \Cron::setLogOnlyErrorJobsToDatabase(true);

    Getter

    To receive the current boolean value of the error job logging, use the static isLogOnlyErrorJobsToDatabase() function.


    Delete old database entries

    Cron can delete old database entries for you. During each run method call, Cron checks if there are old manager and job entries in the database and if the reference value is reached, the entries will be deleted. You can change the reference value by calling the setDeleteDatabaseEntriesAfter function. The default value is 240 hours (10 days). To disable the deletion of old entries just set the reference value to 0.

    public static function setDeleteDatabaseEntriesAfter($hours) {

    Example

    // Set the delete database entries reference value to 10 days (24 hours x 10 days)
    \Cron::setDeleteDatabaseEntriesAfter(240);

    Getter

    To receive the current reference value just use the static getDeleteDatabaseEntriesAfter function.


    Prevent overlapping

    Cron can prevent overlapping. If this is enabled, only one Cron instance can run at the same time. For example if some jobs need 5 minutes for execution but the Cron route will be called every minute, without preventing overlapping two Cron instances will execute jobs at the same time. When running a job twice at the same time, side effects can occur. Cron can avoid such overlaps by using simple locking techniques.

    public static function setEnablePreventOverlapping() {

    Example

    // The configuration could be set via config file with the key 'preventOverlapping' or via method
    \Cron::setEnablePreventOverlapping();
    // Now the Cron run will only run once at the same time
    
    \Cron::setDisablePreventOverlapping();
    // Prevent overlapping is disabled and many Cron run executions are possible at the same time

    Getter

    To receive the current boolean value just use the static isPreventOverlapping function.

    NOTE: To use the overlapping function, Cron needs writing access to the Laravel storage directory. On some Windows machines the lock file cannot be deleted. If you see a delete error message in your log, please disable this feature.


    Events

    Cron supports Laravel events and provides many information about the run status and the job status. With this you can react to errors. Cron supports the following events.

    • cron.collectJobs - fired before run method call to add jobs and to configure Cron. This event is only fired if you use Cron's integrated route or command.
    • cron.beforeRun - fired before run method call to inform that Cron is about to start. Parameter: $runDate.
    • cron.jobError - fired after a job was exectued and this job returned an error (return value is not equal null). Parameter: $name, $return, $runtime, $rundate.
    • cron.jobSuccess - fired after a job was executed and this job did not return an error (return value is equal null). Parameter: $name, $runtime, $rundate.
    • cron.afterRun - fired after the Cron run was finished. Parameter: $rundate, $inTime, $runtime, $errors - number of error jobs, $crons - array of all exectued jobs (with the keys $name, $return, $runtime), $lastRun - array with information of the last Cron run (with the keys $rundate and $runtime). The $lastRun parameter is an empty array, if Cron is called the first time or if database logging is disabled and therefore the $inTime parameter is equals -1.
    • cron.locked - fired if lock file was found. Parameter: $lockfile.

    To subscribe to an event, use Laravels Event facility. The best place for this is the /path/to/laravel/app/start/global.php file.

    \Event::listen('cron.jobError', function($name, $return, $runtime, $rundate){
        \Log::error('Job with the name ' . $name . ' returned an error.');
    });

    Commands

    Cron brings you the following Laravel commands.

    • cron:run - fires the cron.collectJobs event and starts Cron.
    • cron:list - fires the cron.collectJobs event and lists all registered Cron jobs.
    • cron:keygen - generates a security token with 32 characters.

    Reset Cron

    To reset the cron management, call the static reset method. It will reset all variables to the default values.

    public static function reset() {

    Example

    \Cron::add('example1', '* * * * *', function() {
                        // Do some crazy things successfully every minute
                        return null;
                    });
    \Cron::setLogger(new \Monolog\Logger('cronLogger'));
    \Cron::reset();
    // \Cron::remove('example1') === false
    // \Cron::getLogger() === NULL

    Frequently Asked Questions

    Do I really need crontab or an online cronjob service

    Yes, you do. In comparison to a Java application server for example, PHP only runs if it is executed. If crontab or an online cronjob service provider calls PHP and starts the application, Cron can execute the jobs and will start the work. If PHP is not started, the application sleeps and nothing happens.

    What is the best interval to call the route or command?

    The best interval depends on your jobs. If one job should be executed every minute and another every five minutes, the route or command has to be called every minute. In general you have to find the greatest common divisor of your jobs. Please don't forget to change the runInterval config value if the route or command is not called every minute (default value) and if you want to use Cron's in time check.

    Cron is not running properly and returns runtime and inTime with value -1

    By default Cron prevents overlapping. This means that only one Cron instance will run at the same time. If another instance is called, Cron will not run and will return the runtime and inTime parameter with the value -1. On some Windows machines the deletion of the lock file fails and you have to disable this feature. Please have a look at the prevent overlapping section.

    展开全文
  • cron表达式cron生成器

    2018-12-05 17:45:23
    cron表达式cron生成器
  • cron表达式

    万次阅读 2020-09-08 09:40:03
    【1】cron表达式的格式 【2】特殊字符的含义 【3】使用示例 【1】cron表达式的格式 字段 含义 是否必须 可取值 特殊字符 Seconds 秒 是 0-59 ,_*/ Minutes 分 是 0-59 ,_*/ Hours 时 是 0-23 ,_*/ ...

    【1】cron表达式的格式
    【2】特殊字符的含义
    【3】使用示例


    【1】cron表达式的格式

    字段 含义 是否必须 可取值 特殊字符
    Seconds 0-59 ,_*/
    Minutes 0-59 ,_*/
    Hours 0-23 ,_*/
    Day Of month 1-31 ,_*?/LW
    Month 1-12 or JAX-DEC ,_*/
    Day of Week 1-7 or SUN-SAT ,_*?/L#
    Year 1970-2099 ,_*/

    【2】特殊字符的含义

        * (所有值):用于选择该字段的所有可选值,如果在Minuate位则表示每分钟
        ? (非指定的值):当在某些字段需要指定一些值而其他字段不指定时使用。比方说想在一个月的第10天触发,而不关心这天是一周的第几天,则可以在第4位写10而第6位放“?”。
        -  :用于定义范围:第三位写“10-12”指10点、11点、12点。
        ,  :用于指定其他值。比方说,“MON,WED,FRI”在第6位,表示每周一、周三、周五
        /  :用于指定增量。比方说在第1位写"0/15”表示第0、15、30和45秒,而“5/15”表示第5、20、35和50秒。
        L (last):在不同的字段含义不同,在第4位表示每月的最后一天,单字符在第6位表示“7”或者"SAT"。如果在其他字符后,比方说“6L”在第6位表示“当月的最后一个周五”。也可以指定偏移量,比方说“L-3”表示倒数第3天。
        W (周):用于指定给定日期最近的工作日。比方说,在第4位指定“15W”表示“月份中的的第15天最近的工作日”,如果第15天是周日则会在16号触发,如果是周六则在14号触发,如果是工作日则在当天触发。但是需要注意的是,如果设置的是“1W”而第1号是周六,那将在3号触发,即触发是不能跨月的。'W'字符只能用于 ‘day-of-month’是单个一天时,而不能是连续的日期。 'L'和'W'字符经常组合在一起使用‘LW’,表示‘这个月的最后一个工作日’。
        #  :用于指定月份中的第几天。比方说,‘6#3’在‘day-of-week’表示这个月的第三个周五(国外周日是第一天)。
    

    【3】使用示例

    表达式 含义
    0 0 12 * * ? 每天的中午12点触发
    0 15 10 ? * * 每天的10:15触发
    0 15 10 * * ? 每天的10:15触发
    0 15 10 * * ? * 每天的10:15触发
    0 15 10 * * ? 2005 2005年每天的10:15触发
    0 * 14 * * ? 每天的14:00到14:59的每个整分钟触发
    0 0/5 14 * * ? 每天的14:00到14:55中每5分钟触发一次
    0 0/5 14,18 * * ? 每天的14:00到14:55中每5分钟触发一次,18:00到18:55中每5分钟触发一次
    0 0-5 14 * * ? 每天的14:00到14:05中每分钟触发一次
    0 10,44 14 ? 3 WED 3月份的每个周三,在下午的14:10和14:44触发
    0 15 10 ? * MON-FRI 每个周一、周二、周三、周四、周五的上午10:15触发
    0 15 10 15 * ? 每个月的第15天的10:15触发
    0 15 10 L * ? 每个月最后一天的10:15触发
    0 15 10 L-2 * ? 每个月的倒数第三天的10:15触发
    0 15 10 ? * 6L 每个月的最后一个周五的10:15触发
    0 15 10 ? * 6L 2002-2005 在2002、2003、2004、2005年的每个月的最后一个周五的上午10:15触发
    0 15 10 ? * 6#3 每个月的第3个周五的上午10:15触发
    0 0 12 1/5 * ? 在每个月的第一天开始,每隔5天的中午12点触发
    0 11 11 11 11 ? 每年的11月11号的上午11:11触发
    展开全文
  • cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor, ))) The Cron type now accepts functional options on construction rather than the previous ad-hoc ...
  • cron测试工具

    2018-08-13 11:11:38
    cron测试工具,cron测试工具cron测试工具cron测试工具cron测试工具
  • gocron - 定时任务管理系统 项目简介 使用Go语言开发的轻量级定时任务集中调度和管理系统, 用于替代Linux-crontab 查看文档 原有的延时任务拆分为独立项目延迟队列 功能特性 Web界面管理定时任务 crontab时间...
  • golang cron

    2020-11-23 11:47:37
    import ( "github.com/robfig/cron/v3" "log" ) func newWithSecond() *cron.Cron { ... cron.Hour | cron.Dom | cron.Month | cron.DowOptional | cron.Descriptor) return cron.New(cron.WithP.
    import (
       "github.com/robfig/cron/v3"
       "log"
    )
    
    func newWithSecond() *cron.Cron {
       secondParser := cron.NewParser(cron.Second | cron.Minute |
          cron.Hour | cron.Dom | cron.Month | cron.DowOptional | cron.Descriptor)
       return cron.New(cron.WithParser(secondParser), cron.WithChain())
    }
    
    func CreateCron() {
       //初始化一个定时任务
       c := newWithSecond()  //c:=cron.New()
       //定义时间表达式,这里的含义是每天0点执行一次
       spec := "0 0 0 * * ?"
       //给初始化的定时任务指定时间表达式和具体执行的函数
       if _, err := c.AddFunc(spec, MyFunc); err != nil {
          log.Println(err)
       }
       //运行定时任务
       c.Start()
    }
    展开全文
  • cron安装包

    热门讨论 2016-09-27 09:58:59
    crontab是linux操作系统定时任务执行工具,包含两个安装包 vixie-cron和crontabs
  • cron表达式详解,cron表达式写法,cron表达式例子

    万次阅读 多人点赞 2018-01-03 12:55:09
    先了解每个位置代表的含义,在了解每个位置允许的范围,以及一些特殊写法,还有常用的案例,足够你掌握cron表达式
  • 定时任务cron表达式详解

    万次阅读 多人点赞 2018-05-18 11:04:35
    cron表达式顺序秒分钟小时日期月份星期年(可选)取值0-590-590-231-30(31)1-121-7允许特殊字符, - * /, - * /, - * /, - * / ? L W C, - * /, - * / L # C1970-2099, - * /字段含义*:代表所有可能的值-:指定范围,:...
  • Cron表达式

    2019-04-24 16:59:51
    Cron表达式
  • Cron表达式详细解读

    万次阅读 2020-12-14 14:12:45
    cron:读音英 ['krɔ:n]/美 ['krɒn],译为“计划任务”,是任务在约定的时间执行已经计划好的工作,该词来源于希腊语chronos(χρόνος),原意是时间 语法结构 Cron表达式是一个字符串,字符串以5或6个...
  • systemd-cron, 运行cron脚本的systemd单元 systemd-cronsystemd 运行 cron脚本的单元描述systemd单位通过在cron目录中运行脚本来提供cron守护进程功能。这个crontab是自动翻译使用 (/usr)/lib/systemd/system-g
  • cron表达式页面生成

    2018-06-26 00:47:38
    cron表达式页面生成cron表达式页面生成cron表达式页面生成cron表达式页面生成
  • Quartz Cron 表达式生成工具,可以在线编辑,反解析等,html实现,方便引用到各种语言框架的web项目当中,解压即用

空空如也

1 2 3 4 5 ... 20
收藏数 38,162
精华内容 15,264
关键字:

cron