In actual application development, we often need to regularly delete some expired or useless data in order to maintain data cleanliness and database performance. In the ThinkPHP framework, we can easily implement the function of regularly deleting data every day through the Timer class.
The following is the implementation idea:
The specific implementation steps are as follows:
namespace app\test\controller; use think\Controller; use think\Db; use think\facade\Log; class Task extends Controller { public function deleteExpiredData() { $yesterday = date('Y-m-d', strtotime('-1 day')); //获取昨天的日期 $where = ['create_time' => ['<', $yesterday]]; //查询条件 $res = Db::name('test')->where($where)->delete(); //执行数据删除操作 Log::write('删除了'.$res.'条过期数据'); //记录日志 } }
Taking the Test module as an example, query the data in the test table under the Test module that was created earlier than yesterday and delete it, and record the number of deleted data in the log.
use think\console\Command; use think\console\Input; use think\console\Output; use think\facade\Log; use think\console\Schedule; require __DIR__ . '/../thinkphp/base.php'; //载入ThinkPHP框架 //定时任务注册 $schedule = new Schedule(); $schedule->call('app\test\controller\Task@deleteExpiredData') //每天执行deleteExpiredData()方法 ->daily() ->at('00:00'); //指定执行时间 //Timer对象实例化 $timer = new \think\Timer(); $timer->add(86400, function () use ($schedule) { $schedule->run(); //执行定时任务 }); $timer->start(); //启动定时器
Here, a Schedule object is instantiated first , used to manage scheduled tasks. Then specify the task to be executed every day through the daily() method, and specify the task execution time through the at() method, which is 00:00 every day. Then register the scheduled task through the add() method of the Timer object, and specify the execution interval of the task as one day (ie 86400 seconds). Finally, start the timer and wait for the task to be executed.
Summary:
This article introduces specific implementation ideas and steps for the need to delete data regularly every day under the ThinkPHP framework. Among them, the Timer class and Schedule class are mainly used. Through the methods of these classes, the function of executing specified tasks regularly every day is realized, which greatly reduces the development difficulty and workload.
The above is the detailed content of How thinkphp can delete data regularly every day. For more information, please follow other related articles on the PHP Chinese website!