laravel定时任务

Posted 段佳伟的小憩屋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了laravel定时任务相关的知识,希望对你有一定的参考价值。

在项目中遇到定时执行某个php脚本,比如发短信 发邮件之类的

那么该如何写呢?

学习源头:

发送邮件:http://laravelacademy.org/post/1986.html

send方法返回的是空,要用count(Mail::failures()) > 0来判断才对。详见http://stackoverflow.com/questions/35569861/how-to-check-email-sent-or-not-in-laravel-5,文档 https://laravel.com/api/5.1/Illuminate/Mail/Mailer.html#method_failures

注意这里的$flag其实返回的是null;要根据count(Mail::failures()) > 0 时为失败, 输出日志信息

导出excel:http://laravelacademy.org/post/2024.html

这里只需要生成excel即可,不需要导出:

Excel::create(‘学生成绩‘,function($excel) use ($cellData){
     $excel->sheet(‘score‘, function($sheet) use ($cellData){
         $sheet->rows($cellData);
     });
//})->store(‘xls‘)->export(‘xls‘);
})->store(‘xls‘); // 把导出去掉就行

定时任务:http://laravelacademy.org/post/6228.html

https://blog.csdn.net/zhezhebie/article/details/79205414

这里用不用php artisan都可,也可以自己依据示例来创建

<?php
/**
 * 定时发送邮件(预警管理数据报表)
 * User: djw
 * Date: 2018/6/25
 * Time: 17:14
 */

namespace iqiyiConsoleCommands;


use IlluminateConsoleCommand;
use IlluminateSupportFacadesConfig;
use Mail;
use MaatwebsiteExcelFacadesExcel;

class SendWarningLists extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = ‘send.warning.lists‘; // 这里很重要 这是将来执行crontab 是对应的命令名称   不能乱写
  // */1 * * * * /opt/php7/bin/php /home/www/stock/crm/web1/artisan send.warning.lists >> /www/logs/stock.send.warning.lists.log
  // 有参数的写法为
  //
protected $signature = ‘stock.card {do : do what} {do_param : param} ‘;
  // protected $signature = ‘expdown {datas}‘;
  
/** * The console command description. * * @var string */ protected $description = ‘Command description‘; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() // 处理的代码写这里 { $list = iqiyiHttpControllersWarning::listImport(); // 预警管理-库存 //dd($list); $list2 = iqiyiHttpControllersWarning::listExport(); // 渠道库存 // 生成excel $menu_arr = [ ‘import_types‘=>‘卡密类型‘, ‘card_count‘=>‘总数量‘, ‘remain_count‘=>‘剩余数量‘, ‘phone‘=>‘电话‘, ‘user‘=>‘负责人‘, ‘num‘=>‘预警数量‘, ]; // 第一个excel的表头数组 $menu_arr2 = [ ‘channel‘=>‘卡密渠道‘, ‘import_types‘=>‘卡密类型‘, ‘card_count‘=>‘总数量‘, ‘remain_count‘=>‘剩余数量‘, ‘phone‘=>‘电话‘, ‘user‘=>‘负责人‘, ‘num‘=>‘预警数量‘, ]; // 第二个excel的表头数组 // 第一行的表头 foreach($menu_arr as $k=>$v){ $cellData[0][] = $v; } foreach($menu_arr2 as $k=>$v){ $cellData2[0][] = $v; } $list = json_decode(json_encode($list), true); $list2 = json_decode(json_encode($list2), true); // 数据信息 if (!empty($list)) { $i = 1; foreach($list as $k=>$v){ $cellData[$i][] = isset($v[‘import_types‘]) ? $v[‘import_types‘] :‘‘; $cellData[$i][] = isset($v[‘card_count‘]) ? $v[‘card_count‘] :‘‘; $cellData[$i][] = isset($v[‘remain_count‘]) ? $v[‘remain_count‘] :‘‘; $cellData[$i][] = isset($v[‘war‘][‘phone‘]) ? $v[‘war‘][‘phone‘] : ‘‘; $cellData[$i][] = isset($v[‘war‘][‘user‘]) ? $v[‘war‘][‘user‘] : ‘‘; $cellData[$i][] = isset($v[‘war‘][‘num‘]) ? $v[‘war‘][‘num‘] : ‘‘; $i++; } } if (!empty($list2)) { $y = 1; foreach($list2 as $k=>$v){ $cellData2[$y][] = isset($v[‘channel‘]) ? $v[‘channel‘] :‘‘; $cellData2[$y][] = isset($v[‘import_types‘]) ? $v[‘import_types‘] :‘‘; $cellData2[$y][] = isset($v[‘card_count‘]) ? $v[‘card_count‘] :‘‘; $cellData2[$y][] = null !== ($v[‘card_count‘] - $v[‘back_num‘] - $v[‘surplus‘]) ? ($v[‘card_count‘] - $v[‘back_num‘] - $v[‘surplus‘]) :‘‘; $cellData2[$y][] = isset($v[‘war‘][‘phone‘]) ? $v[‘war‘][‘phone‘] : ‘‘; $cellData2[$y][] = isset($v[‘war‘][‘user‘]) ? $v[‘war‘][‘user‘] : ‘‘; $cellData2[$y][] = isset($v[‘war‘][‘num‘]) ? $v[‘war‘][‘num‘] : ‘‘; $y++; } } // 保存为xls文件 Excel::create(date(‘Y-m-d‘)."预警管理-库存 数据报表",function($excel) use ($cellData){ $excel->sheet(‘数据报表‘, function($sheet) use ($cellData){ $sheet->rows($cellData); }); })->store(‘xls‘); // 文件默认保存到storage/exports目录下 Excel::create(date(‘Y-m-d‘)."渠道库存 数据报表",function($excel) use ($cellData2){ $excel->sheet(‘数据报表‘, function($sheet) use ($cellData2){ $sheet->rows($cellData2); }); })->store(‘xls‘); // 文件默认保存到storage/exports目录下 $str = date(‘Y-m-d‘).‘预警管理 数据报表‘; $toarr = Config::get(‘constants.WLRECEIVER‘); foreach ($toarr as $key => $value) { // 这里$flag返回为null 即使成功 $flag = Mail::send(‘mail.sendwarninglists‘, [‘str‘ => $str], function ($message) use($value){ $to = $value; $message->to($to)->subject(date(‘Y-m-d‘).‘预警管理 数据报表‘); $attachment = storage_path(‘exports/‘.date(‘Y-m-d‘)."预警管理-库存 数据报表.xls"); $attachment2 = storage_path(‘exports/‘.date(‘Y-m-d‘)."渠道库存 数据报表.xls"); // chmod($attachment , 0644); //0644 要修改成的权限值 // chmod($attachment2 , 0644); //0644 要修改成的权限值 //在邮件中上传附件 $message->attach($attachment,[‘as‘=>date(‘Y-m-d‘).‘预警管理-库存 数据报表.xls‘]); $message->attach($attachment2,[‘as‘=>date(‘Y-m-d‘).‘渠道库存 数据报表.xls‘]); }); if(count(Mail::failures()) > 0){ // 获取失败收件人的数组 echo " ".date(‘Y-m-d‘)."{$value}发送邮件失败,请重试!"; // 输出的内容 }else{ echo " ".date(‘Y-m-d‘)."{$value}发送邮件成功,请查收!"; } } } }

然后需要在Kernel.php中添加新写的执行代码

<?php

namespace iqiyiConsole;

use IlluminateConsoleSchedulingSchedule;
use IlluminateFoundationConsoleKernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [       
        iqiyiConsoleCommandsimportCard::class,
        iqiyiConsoleCommandsStockCard::class,
        iqiyiConsoleCommandsexpon::class,
        iqiyiConsoleCommandsexpdown::class,
        iqiyiConsoleCommandsWarning::class,
        iqiyiConsoleCommandsOrderBd::class,
        iqiyiConsoleCommandslostorder::class,
        iqiyiConsoleCommandsmonitorqueue::class,
        iqiyiConsoleCommandsCard::class,
        iqiyiConsoleCommandsChannelPriceTip::class,
        iqiyiConsoleCommandsPCard::class,
        iqiyiConsoleCommandsSendWarningLists::class,    ];

    /**
     * Define the application‘s command schedule.
     *
     * @param  IlluminateConsoleSchedulingSchedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command(‘inspire‘)
        //          ->hourly();
//        $schedule->command(‘SendWarningLists‘)->cron(‘1 * * * *‘);
    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        require base_path(‘routes/console.php‘);
    }
}

然后就是再linux上crontab -e

编辑你的定时任务了

0 1 * * * /usr/bin/python /opt/scripts/bakup/bakupwiki.py root 123uway123 wiki >/tmp/mysqllog.txt 2>&1
00 0 * * * /opt/php7/bin/php /www/fee/sandbox/web/artisan monitor
0 3 * * * /www/shell/iqiyi/del.bak.sql.sh >> /www/logs/del.log
#余额提醒
#*/1 * * * * /opt/php7/bin/php /home/www/stock/crm/web1/artisan channel.price.tip >> /www/logs/stock.channel.price.tip.log
#库存补单
#*/1 * * * * /opt/php7/bin/php /home/www/stock/crm/web1/artisan order.bd >> /www/logs/stock.order.bd.log
00 0 * * * /opt/scripts/logrotate/logrotate.sh  > /dev/null 2>&1

#iqiyi 日志 每小时切割
0 */1 * * * /opt/scripts/logrotate/logrotate.hourly.sh  > /dev/null 2>&1
#iqiyi 日志处理
30 * * * * /opt/python3.6/bin/python3 /home/offline/uvpv/index.py  > /dev/null 2>&1
#iback图片备份
0 2 * * * sh /home/iqiyi/bak/iback.bak.sh  > /dev/null 2>&1
#预警管理数据报表每月26日0:00发送邮件
#*/1 * * * * /opt/php7/bin/php /home/www/stock/crm/web1/artisan send.warning.lists >> /www/logs/stock.send.warning.lists.log

大功告成

 






以上是关于laravel定时任务的主要内容,如果未能解决你的问题,请参考以下文章

laravel 任务调度(定时执行任务)

基于supervisor秒级Laravel定时任务

PHP Laravel定时任务Schedule

Laravel框架定时任务2种实现方式示例

laravel创建定时任务

laravel定时任务