Linux+tp crontab 执行定时任务
1、创建一个自定义命令类文件
1 | php think make:command Test |
该命令会生成一个app\command\Test.php命令行指令类
我们修改内容如下:
点击查看代码
<?php
declare (strict_types=1);
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
class Test extends Command
{
protected function configure()
{
// 指令配置
//这里我们定义了一个叫Test的命令,到时候我们运行该Test命令就会执行该文件下面的execute()方法
$this->setName('Test')->setDescription('Say Test');
}
/**
* execute()方法 就是 运行该命令行类的时候要执行的具体业务逻辑代码
*/
protected function execute(Input $input, Output $output)
{
// 指令输出
$output->writeln('Test world');
}
}
2、在config/console.php文件中,进行注册命令
点击查看代码
<?php
// +----------------------------------------------------------------------
// | 控制台配置
// +----------------------------------------------------------------------
return [
// 指令定义
'commands' => [
//Test就是下面要使用 php think 运行的具体命令(即 php think Test),叫什么自己随意命名
//当我们运行php think Test命令后,就会执行app\command\Test类中的execute()方法
'Test' => 'app\command\Test',
],
];
3、运行Test命令
php think Test
输出
Test world
4 在tp 项目根目录,新建test.sh文件,内容如下:
点击查看代码
#!/bin/sh
#运行文件,测试,普通模式运行
/www/server/php/70/bin/php /www/wwwroot/域名/think test
#其他模式,指定用户组执行
#/usr/bin/su -c '/www/server/php/70/bin/php /www/wwwroot/域名/think test' www;
5、编写crontab定时任务文件,将Test命令 添加到定时任务中
点击查看代码
# 1、编辑crontab定时任务文件
crontab -e
# 2、连接linux服务器,登陆进去,执行crontab -l 查看是否有设置定时任务,crontab -e 编辑定时任务,内容步骤如下:
crontab -e 加入以下内容
如果你想把日志分成每天来单独记录,可以这样写:
*/1 * * * * /www/wwwroot/域名/test.sh >> /www/log/test_`date -d 'today' +\%Y-\%m-\%d`.log 2>&1
6、总结
类库文件名字请自行定义
自己的业务逻辑代码写在app\command\Test中execute()
在config/console.php注册对应的命令将命令添加到crontab定时任务中
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战