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 >&
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('foo@example.com');
Note: The
emailOutputToandsendOutputTomethods are exclusive to thecommandmethod and are not supported forcall.
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"
Task Scheduling的更多相关文章
- 动态规划——独立任务最优调度(Independent Task Scheduling)
题目链接 题目描述 用2 台处理机A 和B 处理n 个作业.设第i 个作业交给机器A 处理时需要时间i a ,若由机器B 来处理,则需要时间i b .由于各作业的特点和机器的性能关系,很可能对于某些i ...
- 题解 AT4170 【[ABC103A] Task Scheduling Problem】
翻译 有 \(3\) 个正整数 \(a\).\(b\).\(c\),请你输出这 \(3\) 个数中的最大值 \(-\) 最小值的差. 分析 求最大值 \(-\) 最小值的差,我们自然可以使用 for ...
- SQL Server 2012中Task是如何调度的?
SQL Server 2012中Task是如何调度的?[原文来自:How It Works: SQL Server 2012 Database Engine 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- ...
- A Complete List of .NET Open Source Developer Projects
http://scottge.net/2015/07/08/a-complete-list-of-net-open-source-developer-projects/?utm_source=tuic ...
- MapReduce的核心资料索引 [转]
转自http://prinx.blog.163.com/blog/static/190115275201211128513868/和http://www.cnblogs.com/jie46583173 ...
- Docker on YARN在Hulu的实现
这篇文章是我来Hulu这一年做的主要工作,结合当下流行的两个开源方案Docker和YARN,提供了一套灵活的编程模型,目前支持DAG编程模型,将会支持长服务编程模型. 基于Voidbox,开发者可以很 ...
- Swoole + zphp 改造为专门用来开发接口的框架
The other problem I had with Laravel Task Scheduling was that i really only wanted something to hand ...
- Mistral 工作流组件之一 概述
Mistral的前世今生: Mistral是Mirantis公司为Openstack开发的工作流组件,提供Workflow As a Service.典型的应用场景包括任务计划服务Cloud Cro ...
随机推荐
- Vc++内存布局
Vc++内存布局 测试平台 Windows server 2012 R2 and visual studio 2013 professional. 本篇文章意在介绍vc++中类的内存布局方式,只是研究 ...
- 【Python】爬取理想论坛单帖爬虫
代码: # 单帖爬虫,用于爬取理想论坛帖子得到发帖人,发帖时间和回帖时间,url例子见main函数 from bs4 import BeautifulSoup import requests impo ...
- (剑指Offer)面试题41:和为s的连续正数序列
题目: 输入一个正数s,打印出所有和为s的连续正数序列(至少含有两个数).例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以结果打印出3个连续序列1-5,,4-6和7-8. 思路: ...
- C++ 生成
1.重新生成,会导致所有cpp文件重新编译,然后连接. 2.使用生成,只会对需要重新编译的cpp文件,进行编译. a.修改cpp文件方法实现,只需要重新编译该cpp文件 b.修改h文件的接口部分,包含 ...
- Chrome插件-把网页图片上传到七牛空间一
功能:图片上右键,点击上传图片到七牛,把图片上传的指定空间并返回图片URL. Chrome插件本质就是js代码,但是里面有一些限制,比如事件绑定等和普通js的绑定是有区别的,主要是为了安全性考虑. 做 ...
- java对象的强引用,软引用,弱引用和虚引用
1.强引用 以前我们使用的大部分引用实际上都是强引用,这是使用最普遍的引用.如果一个对象具有强引用,那就类似于必不可少的生活用品,垃圾回收器绝不会回收它.当内存空 间不足,Java虚拟机宁愿抛出Out ...
- mysql基础知识之-数据库的创建、查看等常用操作
命令创建mysql数据库: 先启动mysql数据库,连接数据库: mysql -uroot -p123456 (语法:mysql -u登录名 -p密码) 创建表: create dat ...
- MySQL联合多表更新和删除
多表更新 在 MySQL 3.23 中,你能够使用 LIMIT # 来确保仅仅有给定的记录行数目被更改. 假设一个 ORDER BY 子句被使用(从 MySQL 4.0.0 開始支持),记录行将以指定 ...
- ajax 缓存问题及解决方案
ajax 缓存问题及解决方案 CreationTime--2018年7月25日16点04分 Author:Marydon 1.什么情况下ajax请求会出现缓存? 当请求的路径.参数名.参数值三者都 ...
- oracle修改用户密码过期时间
Oracle默认在default概要文件中设置了“PASSWORD_LIFE_TIME=180天”,导致密码过期,程序无法使用,业务进程会提示无法连接数据库等字样. --查询默认密码过期时间 SELE ...