学习路之PHP--thinkphp5+windows服务器实现定时任务

一、简介

最近有个需求就是实现一个定时任务,在每天上午8点给当天生日的员工发送生日祝福,语言为php,框架为thinkphp5,服务器使用的是windows系统。

二、思路

使用tp5的command.php创建一个自定义命令行命令remind。Remind方法执行发送生日祝福的业务逻辑。
创建remind.bat的批处理文件,内容为调用第一步中生成的自定义命令行命令。
在windos服务器,创建批处理任务,每天在8点执行一次第二步中创建的批处理文件。
三、具体实现过程

1.生成自定义命令行命令,remind

(1)配置 命令行工具配置文件,文件位置为project/application/command.php
 

<?php
//命令类文件的位置
return ['app\admin\command\Remind',];

(2)创建命令类文件 

<?php
namespace app\admin\command;
 
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Session;
class Remind extends Command
{
    protected function configure()
{
//setName为定义命令名称
//setDescription定义描述
        $this->setName('remind')->setDescription('Send birthday wishes to employees on their birthday');
    }
//重写execute方法 是用命令最终执行的方法。
    protected function execute(Input $input, Output $output)
    {
        $output->writeln($this->remind_send());
    }
 
//生日祝福发送的业务逻辑
    protected function remind_send(){
      //数据库存放的为时间戳格式,找到当天生日的用户。
      $sql = "SELECT * FROM `znote_user` WHERE MONTH(FROM_UNIXTIME(birthday,'%Y-%m-%d %H:%i:%s')) = MONTH(NOW()) and DAY(FROM_UNIXTIME(birthday,'%Y-%m-%d %H:%i:%s')) = DAY(NOW())";
    	$users = Db::query($sql);
      $email_util = controller('index/email');
      foreach($users as $user){
          $email = $user['email'];
          $content = "尊敬的".$user['username']."先生:<br>&nbsp;&nbsp;系统检测到今天是您的生日,为您送上诚挚的生日祝福,祝您身体快乐";
          $email_util->sendMail($email,$content,'生日祝福');
      }
    	return json_encode($users, true);
    }
}

(3)检查自定义命令是否可以直接运行

找到项目根目录,在项目根目录中执行php think remind

查看运行结果。

2.创建remind.bat的批处理文件

remind.bat 批处理文件的内容为(根据自己的根目录位置自行更改内容,我的根目录在D盘, D:\phpStudy\PHPTutorial\WWW\note为根目录位置。remind为自定义命令行命令)

d:
cd D:\phpStudy\PHPTutorial\WWW\note
php think remind

3.创建windows定时任务 

创建定时任务请参考以下网址,不在做赘述。

https://jingyan.baidu.com/article/154b463130041128ca8f41c7.html

原文链接:http://www.jhone.top/index/index/toread.html?article_id=5
————————————————
版权声明:本文为CSDN博主「残城碎梦」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_42232296/article/details/108824682

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值