Task Scheduling

Introduction

In the past, developers have generated a Cron entry for each task they need to schedule. However, this is a headache. Your task schedule is no longer in source control, and you must SSH into your server to add the Cron entries. The Laravel command scheduler allows you to fluently and expressively define your command schedule within Laravel itself, and only a single Cron entry is needed on your server.

Your task schedule is defined in the app/Console/Kernel.php file‘s schedule method. To help you get started, a simple example is included with the method. You are free to add as many scheduled tasks as you wish to the Schedule object.

Starting The Scheduler

Here is the only Cron entry you need to add to your server:

* * * * * php /path/to/artisan schedule:run >> /dev/null 2>&1

This Cron will call the Laravel command scheduler every minute. Then, Laravel evaluates your scheduled tasks and runs the tasks that are due.

Defining Schedules

You may define all of your scheduled tasks in the schedule method of theApp\Console\Kernel class. To get started, let‘s look at an example of scheduling a task. In this example, we will schedule a Closure to be called every day at midnight. Within the Closure we will execute a database query to clear a table:

<?php

namespace App\Console;

use DB;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \App\Console\Commands\Inspire::class,
    ];

    /**
     * Define the application‘s command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->call(function () {
            DB::table(‘recent_users‘)->delete();
        })->daily();
    }
}

In addition to scheduling Closure calls, you may also schedule Artisan commands and operating system commands. For example, you may use the command method to schedule an Artisan command:

$schedule->command(‘emails:send --force‘)->daily();

The exec command may be used to issue a command to the operating system:

$schedule->exec(‘node /home/forge/script.js‘)->daily();

Schedule Frequency Options

Of course, there are a variety of schedules you may assign to your task:

Method Description
->cron(‘* * * * *‘); Run the task on a custom Cron schedule
->everyMinute(); Run the task every minute
->everyFiveMinutes(); Run the task every five minutes
->everyTenMinutes(); Run the task every ten minutes
->everyThirtyMinutes(); Run the task every thirty minutes
->hourly(); Run the task every hour
->daily(); Run the task every day at midnight
->dailyAt(‘13:00‘); Run the task every day at 13:00
->twiceDaily(1, 13); Run the task daily at 1:00 & 13:00
->weekly(); Run the task every week
->monthly(); Run the task every month
->yearly(); Run the task every year

These methods may be combined with additional constraints to create even more finely tuned schedules that only run on certain days of the week. For example, to schedule a command to run weekly on Monday:

$schedule->call(function () {
    // Runs once a week on Monday at 13:00...
})->weekly()->mondays()->at(‘13:00‘);

Below is a list of the additional schedule constraints:

Method Description
->weekdays(); Limit the task to weekdays
->sundays(); Limit the task to Sunday
->mondays(); Limit the task to Monday
->tuesdays(); Limit the task to Tuesday
->wednesdays(); Limit the task to Wednesday
->thursdays(); Limit the task to Thursday
->fridays(); Limit the task to Friday
->saturdays(); Limit the task to Saturday
->when(Closure); Limit the task based on a truth test

Truth Test Constraints

The when method may be used to limit the execution of a task based on the result of a given truth test. In other words, if the given Closure returns true, the task will execute as long as no other constraining conditions prevent the task from running:

$schedule->command(‘emails:send‘)->daily()->when(function () {
    return true;
});

When using chained when methods, the scheduled command will only execute if allwhen conditions return true.

Preventing Task Overlaps

By default, scheduled tasks will be run even if the previous instance of the task is still running. To prevent this, you may use the withoutOverlapping method:

$schedule->command(‘emails:send‘)->withoutOverlapping();

In this example, the emails:send Artisan command will be run every minute if it is not already running. The withoutOverlapping method is especially useful if you have tasks that vary drastically in their execution time, preventing you from predicting exactly how long a given task will take.

Task Output

The Laravel scheduler provides several convenient methods for working with the output generated by scheduled tasks. First, using the sendOutputTo method, you may send the output to a file for later inspection:

$schedule->command(‘emails:send‘)
         ->daily()
         ->sendOutputTo($filePath);

If you would like to append the output to a given file, you may use the appendOutputTomethod:

$schedule->command(‘emails:send‘)
         ->daily()
         ->appendOutputTo($filePath);

Using the emailOutputTo method, you may e-mail the output to an e-mail address of your choice. Note that the output must first be sent to a file using the sendOutputTo method. Also, before e-mailing the output of a task, you should configure Laravel‘s e-mail services:

$schedule->command(‘foo‘)
         ->daily()
         ->sendOutputTo($filePath)
         ->emailOutputTo(‘[email protected]‘);

Note: The emailOutputTo and sendOutputTo methods are exclusive to the commandmethod and are not supported for call.

Task Hooks

Using the before and after methods, you may specify code to be executed before and after the scheduled task is complete:

$schedule->command(‘emails:send‘)
         ->daily()
         ->before(function () {
             // Task is about to start...
         })
         ->after(function () {
             // Task is complete...
         });

Pinging URLs

Using the pingBefore and thenPing methods, the scheduler can automatically ping a given URL before or after a task is complete. This method is useful for notifying an external service, such as Laravel Envoyer, that your scheduled task is commencing or complete:

$schedule->command(‘emails:send‘)
         ->daily()
         ->pingBefore($url)
         ->thenPing($url);

Using either the pingBefore($url) or thenPing($url) feature requires the Guzzle HTTP library. You can add Guzzle to your project by adding the following line to yourcomposer.json file:

"guzzlehttp/guzzle": "~5.3|~6.0"
时间: 2024-10-13 09:19:18

Task Scheduling的相关文章

Power aware dynamic scheduling in multiprocessor system employing voltage islands

Minimizing the overall power conservation in a symmetric multiprocessor system disposed in a system-on-chip (SoC) depends on using voltage islands operated at different voltages such that similar circuits will perform at significantly different level

【安全牛学习笔记】&#8203;NMAP

NMAP ╋━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋ ┃NMAP                                                                                              ┃ ┃nmap扫描脚本                                                                                   

System and method for dynamically adjusting to CPU performance changes

FIELD OF THE INVENTION The present invention is related to computing systems, and more particularly to a system and method for adjusting to changes in processor performance. BACKGROUND INFORMATION Designers of mobile computing platforms are faced wit

Linux内核抢占机制 - 简介

本文首发于 http://oliveryang.net,转载时请包含原文或者作者网站链接. 本文主要围绕 Linux 内核调度器 Preemption 的相关实现进行讨论.其中涉及的一般操作系统和 x86 处理器和硬件概念,可能也适用于其它操作系统. 1. 背景知识 要深入理解 Preemption 必须对操作系统的 Context Switch 做一个全面的梳理.最终可以了解 Preemption 和 Context Switch 概念上的区别与联系. 1.1 Context Switch C

Docker on YARN在Hulu的实现

这篇文章是我来Hulu这一年做的主要工作,结合当下流行的两个开源方案Docker和YARN,提供了一套灵活的编程模型,目前支持DAG编程模型,将会支持长服务编程模型. 基于Voidbox,开发者可以很容易的写出一个分布式的框架,Docker作为运行的执行引擎,YARN作为集群资源的管理系统. 同时这篇文章也发表在Hulu官方的技术博客上:http://tech.hulu.com/blog/2015/08/06/voidbox-docker-on-yarn/ 1. Voidbox Motivati

Method, apparatus and system for acquiring a global promotion facility utilizing a data-less transaction

A data processing system includes a global promotion facility and a plurality of processors coupled by an interconnect. In response to execution of an acquisition instruction by a first processor among the plurality of processors, the first processor

HDFS分布式文件系统(The Hadoop Distributed File System)

The Hadoop Distributed File System (HDFS) is designed to store very large data sets reliably, and to stream those data sets at high bandwidth to user applications. In a large cluster, thousands of servers both host directly attached storage and execu

Linux Kernel 排程機制介紹

http://loda.hala01.com/2011/12/linux-kernel-%E6%8E%92%E7%A8%8B%E6%A9%9F%E5%88%B6%E4%BB%8B%E7%B4%B9/ Linux Kernel 排程機制介紹 Linux Kernel 排程機制介紹 [email protected] by loda. 2011/12/2 多核心架構儼然是目前智慧型手機方案的新趨勢,隨著省電與效能上的考量,多核心的架構各家方案也都有所差異.為能讓同一個Linux Kernel在不同效

Mistral 工作流组件之一 概述

Mistral的前世今生:  Mistral是Mirantis公司为Openstack开发的工作流组件,提供Workflow As a Service.典型的应用场景包括任务计划服务Cloud Cron,任务调度Task Scheduling, 复杂的运行时间长的业务流程等.对应的是AWS的SWS(Simple Workflow Serivce). Mistral的核心概念有如下几个: Workbook Workflow Task Action Workflow Execution Workbo