Home php教程 php手册 Execute PHP scripts regularly under Linux (detailed explanation of how to use crontab regularly)

Execute PHP scripts regularly under Linux (detailed explanation of how to use crontab regularly)

Jul 09, 2016 am 09:10 AM
crontab linux php code Open source programming programming language Script software development

Detailed explanation of how to use crontab for scheduled execution
How to use:
crontab [ -u user ] filecrontab [ -u user ] { -l | -r | -e }
Description:
Crontab is used to allow users to execute programs at fixed times or fixed intervals. In other words, it is similar to the user's schedule. -u user refers to setting the schedule of the specified user. The premise is that you must have its permissions (for example, root) to specify other people's schedules. If -u user is not used, it means setting your own schedule.
Parameters:

-e: Execute a text editor to set the schedule. The default text editor is VI. If you want to use another text editor, please set the VISUAL environment variable to specify which text editor to use (for example setenv VISUAL joe)
-r: Delete the current schedule
-l: List the current schedule

The format of the schedule is as follows:
f1 f2 f3 f4 f5 program

Where f1 represents minutes, f2 represents hours, f3 represents the day of a month, f4 represents the month, and f5 represents the day of the week. program represents the program to be executed.
When f1 is *, it means the program will be executed every minute, when f2 is *, it means the program will be executed every hour, and so on
When f1 is a-b, it means that it will be executed from the a-th minute to the b-th minute. When f2 is a-b, it means that it will be executed from the a-th hour to the b-th hour, and so on.
​When f1 is */n, it means that it will be executed every n minutes. When f2 is */n, it means it will be executed every n hours. The rest can be deduced
When f1 is a, b, c,..., it means that the a, b, c,... minutes are to be executed. When f2 is a, b, c,..., it means that the a, b, c... It takes hours to execute, and so on for the rest
Users can also store all settings in a file first and use crontab file to set the schedule.
Example:
Execute /bin/ls:
at the 0th minute of every hour every day of the month 0 7 * * * /bin/ls

Within 12 months, /usr/bin/backup will be executed every 20 minutes from 6 am to 12 am every day:
0 6-12/3 * 12 * /usr/bin/backup

​Send a letter to admin
@domain.name:
every day from Monday to Friday at 5:00 pm 0 17 * * 1-5 mail -s "hi"
admin@domain.name
​Execute echo "haha"
at midnight every day of the month at 0:20, 2:20, 4:20.... 20 0-23/2 * * * echo "haha"

Note:
When the program is executed at the time you specify, the system will send you a letter showing the contents of the program execution. If you do not want to receive such a letter, please add > /dev after each line with a space. /null 2>&1 will do.

There are basically two ways to create routine commands in crontab :

One is for all users, who can issue work schedules through the crontab -e command;
The other is for system administrators. You can directly modify the /etc/crontab file to directly execute it regularly.
If you need to send a letter to yourself at 12:00 noon every day,
#crontab -e
Enter the vi editing screen to edit your routine commands, enter the following statement
0 12 * * * mail xxx@163.com
There are 5 numbers above, which mean:
Points (0-59)
Hours (0-23)
Date (1-31)
Month (1-12)
Week(0-6)
In addition, if it is [*], it means that all numbers are applicable.
So, the above statement is to execute the command mail xxx@163.com
Example 1:
Send an email to your friend. It will be sent at 23:59 on May 1st. Use:
# crontab -e 59 23 1 5 * mail xxx@163.com
Example 2:
To check related files every 6 minutes, use:
# crontab -e */6 * * * * /home/cheney/test.sh

Delete routine commands:
# crontab -r will delete it

cron
In Linux, tasks can be configured to run automatically during a specified time period, on a specified date, or when the average system load falls below a specified amount. Red Hat Enterprise Linux is preconfigured to run critical system tasks so that the system can be kept updated. For example, the slocate database used by the locate command is updated daily. System administrators can use automated tasks to perform scheduled backups, monitor systems, run custom scripts, and more.

Red Hat Enterprise Linux comes with several tools to automate tasks: cron, at, and batch.

Cron is a daemon process that can be used to schedule the execution of recurring tasks based on a combination of time, date, month, and week.

cron assumes the system is running continuously. If the system is not running when a task is scheduled, the task will not be executed.

To use the cron service, you must have the vixie-cron RPM package installed and the crond service must be running. To determine whether the package is installed, use the rpm -q vixie-cron command. To determine whether the service is running, use the /sbin/service crond status command.

Configure cron tasks

The main configuration file of cron is /etc/crontab, which includes the following lines:

<tt class="COMPUTEROUTPUT">SHELL=/bin/bash
            PATH=/sbin:/bin:/usr/sbin:/usr/bin
            MAILTO=root
            HOME=/
            # run-parts
            01 * * * * root run-parts /etc/cron.hourly
            02 4 * * * root run-parts /etc/cron.daily
            22 4 * * 0 root run-parts /etc/cron.weekly
            42 4 1 * * root run-parts /etc/cron.monthly</tt>
Copy after login

The first four lines are variables used to configure the cron task running environment. SHELL The value of the variable tells the system which shell environment to use (in this case, bash shell); PATH The variable definition is used The path to execute the command. The output of the cron job is mailed to the username defined by the MAILTO variable. If the MAILTO variable is defined as a blank string (MAILTO=""), the email will not be sent. The HOME variable can be used to set the home directory used when executing commands or scripts.

/etc/crontab Each line in the file represents a task, and its format is:

<tt class="COMPUTEROUTPUT">minute   hour   day   month   dayofweek   command</tt>
Copy after login

 

  • minute — 分钟,从 0 到 59 之间的任何整数

  • hour — 小时,从 0 到 23 之间的任何整数

  • day — 日期,从 1 到 31 之间的任何整数(如果指定了月份,必须是该月份的有效日期)

  • month — 月份,从 1 到 12 之间的任何整数(或使用月份的英文简写如 jan、feb 等等)

  • dayofweek — 星期,从 0 到 7 之间的任何整数,这里的 0 或 7 代表星期日(或使用星期的英文简写如 sun、mon 等等)

  • command — 要执行的命令(命令可以是 ls /proc >> /tmp/proc 之类的命令,也可以是执行你自行编写的脚本的命令。)

在以上任何值中,星号(*)可以用来代表所有有效的值。譬如,月份值中的星号意味着在满足其它制约条件后每月都执行该命令。

整数间的短线(-)指定一个整数范围。譬如,1-4 意味着整数 1、2、3、4。

用逗号(,)隔开的一系列值指定一个列表。譬如,3, 4, 6, 8 标明这四个指定的整数。

正斜线(/)可以用来指定间隔频率。在范围后加上 /<integer> 意味着在范围内可以跳过 integer。譬如,0-59/2 可以用来在分钟字段定义每两分钟。间隔频率值还可以和星号一起使用。例如,*/3 的值可以用在月份字段中表示每三个月运行一次任务。

开头为井号(#)的行是注释,不会被处理。

如你在 /etc/crontab 文件中所见,它使用 run-parts 脚本来执行 /etc/cron.hourly/etc/cron.daily/etc/cron.weekly/etc/cron.monthly 目录中的脚本,这些脚本被相应地每小时、每日、每周、或每月执行。这些目录中的文件应该是 shell 脚本。

如果某 cron 任务需要根据调度来执行,而不是每小时、每日、每周、或每月地执行,它可以被添加到 /etc/cron.d 目录中。该目录中的所有文件使用和 /etc/crontab 中一样的语法。

<tt class="COMPUTEROUTPUT"># record the memory usage of the system every monday
            # at 3:30AM in the file /tmp/meminfo
            30 3 * * mon cat /proc/meminfo >> /tmp/meminfo
            # run custom script the first day of every month at 4:10AM
            10 4 1 * * /root/scripts/backup.sh</tt>
Copy after login

Example 37-1. crontab example

Users other than root can use the crontab tool to configure cron tasks. All user-defined crontabs are saved in the /var/spool/cron directory and executed using the identity of the user who created them. To create a crontab project as a user, log in as that user and type the crontab -e command using either the VISUAL or EDITOR The editor specified by the environment variable to edit the user's crontab. This file uses the same format as /etc/crontab. When the changes to the crontab are saved, the crontab file is saved according to the username and written to the file /var/spool/cron/username in.

The

cron daemon checks every minute the /etc/crontab file, the etc/cron.d/ directory, and the directory. 🎜>/var/spool/cron

Changes in the directory. If changes are found, they are loaded into memory. This way, you don't have to restart the daemon when a crontab file changes.

Control the use of cron

The /etc/cron.allow and /etc/cron.deny files are used to restrict the use of cron. Both formats using control files are one user per line. No spaces are allowed in both files. The cron daemon (crond

) does not have to be restarted if the usage control file is modified. Use a control file that is read every time a user adds or removes a cron task.

Root can always use cron regardless of what is specified in the usage control file.

If the cron.allow file exists, only users listed in it are allowed to use cron, and cron.deny

The file will be ignored.

If the cron.allow file does not exist, all users listed in cron.deny

are banned from using cron .

Start and stop services

To start the cron service, use the /sbin/service crond start command. To stop the service, use the /sbin/service crond stop

command. It is recommended that you start this service at boot time.
Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

The Future of C  : Adaptations and Innovations The Future of C : Adaptations and Innovations Apr 27, 2025 am 12:25 AM

The future of C will focus on parallel computing, security, modularization and AI/machine learning: 1) Parallel computing will be enhanced through features such as coroutines; 2) Security will be improved through stricter type checking and memory management mechanisms; 3) Modulation will simplify code organization and compilation; 4) AI and machine learning will prompt C to adapt to new needs, such as numerical computing and GPU programming support.

How to understand DMA operations in C? How to understand DMA operations in C? Apr 28, 2025 pm 10:09 PM

DMA in C refers to DirectMemoryAccess, a direct memory access technology, allowing hardware devices to directly transmit data to memory without CPU intervention. 1) DMA operation is highly dependent on hardware devices and drivers, and the implementation method varies from system to system. 2) Direct access to memory may bring security risks, and the correctness and security of the code must be ensured. 3) DMA can improve performance, but improper use may lead to degradation of system performance. Through practice and learning, we can master the skills of using DMA and maximize its effectiveness in scenarios such as high-speed data transmission and real-time signal processing.

How to handle high DPI display in C? How to handle high DPI display in C? Apr 28, 2025 pm 09:57 PM

Handling high DPI display in C can be achieved through the following steps: 1) Understand DPI and scaling, use the operating system API to obtain DPI information and adjust the graphics output; 2) Handle cross-platform compatibility, use cross-platform graphics libraries such as SDL or Qt; 3) Perform performance optimization, improve performance through cache, hardware acceleration, and dynamic adjustment of the details level; 4) Solve common problems, such as blurred text and interface elements are too small, and solve by correctly applying DPI scaling.

macOS vs. Linux: Exploring the Differences and Similarities macOS vs. Linux: Exploring the Differences and Similarities Apr 25, 2025 am 12:03 AM

macOSandLinuxbothofferuniquestrengths:macOSprovidesauser-friendlyexperiencewithexcellenthardwareintegration,whileLinuxexcelsinflexibilityandcommunitysupport.macOS,developedbyApple,isknownforitssleekinterfaceandecosystemintegration,whereasLinux,beingo

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

How to uninstall MySQL and clean residual files How to uninstall MySQL and clean residual files Apr 29, 2025 pm 04:03 PM

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

See all articles