tp5定时任务
第一步:
a.App/模块/ 下创建command文件夹
b.我这边是创建在crontab模块里面,在command文件夹下创建一个Task.php文件(具体名字自己根据需求定)
c.复制下面的代码到Task.php
<?php namespace app\crontab\command; use think\console\Command; use think\console\Input; use think\console\input\Argument; use think\console\input\Option; use think\console\Output; use think\Db; class Task extends Command { protected function configure() { $this->setName('task') ->setDescription('定时计划测试:每分钟插入一条数据'); } protected function execute(Input $input, Output $output) { // 输出到日志文件 $output->writeln("TestCommand:"); // 定时器需要执行的内容 $data = [ 'name'=>'zxm22', 'addr'=>'上海' ]; db('blog')->insert($data); $output->writeln("end...."); } }
第二步:在APP/command.php里面加上
第三步:在linux下设置crontab定时计划任务(我的项目文件放在/var/www/mytp5)即可
crontab -l //计划任务列表
crontab -e //编辑新增
crontab -r //删除
可参照:(查看php执行路径 whereis php)
1、配置command.php文件,目录在application/command.php 2、建立命令类文件,新建application/index/command/Test.php <?php namespace app\index\command; use think\console\Command; use think\console\Input; use think\console\Output; class Test extends Command { protected function configure() { $this->setName('test')->setDescription('Here is the remark '); } protected function execute(Input $input, Output $output) { $output->writeln("TestCommand:"); } } 3、命令行下运行php think test ,将输出 TestCommand:,说明命令行已经成功 4、在linux系统配置crontab定时任务,一般目录在下图 4、根据自己的用户角色,编辑文件,如我是root用户,打开root文件,配置contab */1 * * * * cd /项目路径 && /php路径/php think test >> tmp/test.log 2>&1 这句话的意思是没一分钟执行一遍 test/index,日志存储在项目目录的 tmp/test.log文件里 根据上面的步骤就可以把定时任务跑起来了,很简单吧!!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏