Home  >  Article  >  Backend Development  >  How to implement scheduled tasks in PHP and its applications

How to implement scheduled tasks in PHP and its applications

WBOY
WBOYOriginal
2023-06-18 12:13:222306browse

With the development of the Internet and the advancement of technology, the functions of the website are becoming more and more powerful. For some tasks that need to be performed regularly, such as scheduling emails, cleaning logs, etc., it is necessary to use scheduled tasks to automatically perform these tasks. As a scripting language that runs on the server side, PHP is often used for web development and can also implement scheduled tasks. This article will introduce the methods and applications of PHP to implement scheduled tasks.

1. Implementation method

PHP can implement scheduled tasks through the Cron service that comes with the Linux system or by using a third-party class library. Below we will introduce their implementation and usage one by one.

  1. Cron service

Cron service is a scheduled task service that comes with the Linux system. It can execute some specified commands or scripts regularly. To use the Cron service, you need to edit the timer configuration file.

Enter the following command in the terminal to edit the configuration file:

crontab -e

After editing is completed, save and exit. The Cron service will execute the corresponding commands or scripts according to the scheduled tasks in the configuration file. .

The following is the format of the Cron service timer configuration file:

* * * * * command

The Cron service timer is divided into five parts, representing minutes, hours, days, months, and weeks, and their values The ranges are 0-59, 0-23, 1-31, 1-12, 0-7 (0 and 7 are both Sundays). In addition to these five parts, there is also a command part, which represents the command or script that needs to be executed.

For example, in order to run a myscript.sh script at 11pm every night, we can edit the timer configuration file like this:

0 23 * * * /path/to/myscript.sh

This timer means to execute myscript at 11pm every night .sh script.

  1. Third-party class library

In addition to using the Cron service, we can also use third-party class libraries to implement scheduled tasks. These class libraries usually provide richer functions, such as task scheduling, concurrency control, etc.

The following is an introduction to two commonly used third-party libraries.

(1) Cron

Cron is a PHP scheduled task library, which provides a simple task scheduling function. A task can be a SQL statement, a method or an anonymous function. The Cron class library can easily implement scheduled task settings and logging functions.

The steps to use the Cron class library are as follows:

① Installation

The Cron class library can be installed through Composer, open the terminal and enter the following command:

composer require dragonmantank/cron-expression

②Writing code

Next, we create a test.php file to show an example of using the Cron class library. Our task is to output one line of "Hello World!" every minute.

<?php

require_once './vendor/autoload.php';

$cron = new CronCronExpression('* * * * *');

// 每分钟运行一次
if ($cron->isDue()) {
    echo 'Hello World!' . PHP_EOL;
}

The above code first introduces the Cron class library through Composer, and then creates a CronExpression object. The time of the scheduled task is passed into the instantiated object through a string, such as ' ' represents the execution of tasks every minute. In addition, there are also '0 1 ' which represents the execution of tasks at 1 am every day.

The isDue() method checks whether the task we set needs to be executed.

(2) PHP Task Scheduler

In addition to the Cron class library, there is also a task scheduler suitable for PHP - PHP Task Scheduler (PHP Task Scheduler), which can Run CLI (Command Line Interface) commands, execute PHP scripts, call Shell commands or APIs, etc. The PHP task scheduler is very convenient to use. You can set the task execution time, calling method, etc. according to your needs.

The steps to use PHP Task Scheduler are as follows:

① Installation

PHP Task Scheduler can be installed through Composer, open the terminal and enter the following command:

composer require lizhichao/task-scheduler

②Writing code

The same is done to create a test.php file to show how to scaffold the PHP task scheduler.

<?php

require_once './vendor/autoload.php';

use OvertrueEasySchedulingSchedule;

$schedule = new Schedule;

$schedule -> exec('echo "Hello World!"') -> everyMinute();

The above code introduces the PHP task scheduler class library, instantiates a task plan, uses the exec method to add a task, and runs it once every minute.

2. Application Scenarios

PHP’s scheduled task function can be widely used in website operation and maintenance management and background task execution. Below we will introduce some common application scenarios.

  1. Clean logs

The log files of the website usually occupy a lot of disk space. In order to avoid taking up too much disk space, we can clean the log files through scheduled tasks. Clean up.

Use Cron service to implement:

0 0 * * * rm /path/to/log/*.log

Use PHP task scheduler to implement:

$schedule -> exec('rm /path/to/log/*.log') -> daily();

The above code realizes the cleaning of /path/to/log path at 0 o'clock every morning All .log files.

  1. Send emails

Scheduled tasks can also be used to plan to send emails, such as sending news information or promotional information regularly. Using PHP's third-party class library can more conveniently implement SMTP email push service.

Use Cron service to implement:

0 8 * * * php /path/to/send_email.php

Where send_email.php is our script for sending emails regularly.

Use Cron class library to implement:

$cron = new CronExpression('0 8 * * *');
if ($cron->isDue()) {
    // your email sending code
}

Use PHP task scheduler to implement:

$schedule->exec('php /path/to/send_email.php')->dailyAt('08:00');

The above code implements the task of sending emails at 8 o'clock every morning.

3. Summary

This article introduces the method and application scenarios of using Cron service and third-party class library to implement PHP scheduled tasks. Scheduled tasks can help us save a lot of repetitive work and improve work efficiency. In the process of using scheduled tasks, we need to pay attention to issues such as task time settings and task execution log records.

The above is the detailed content of How to implement scheduled tasks in PHP and its applications. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn