Title: Using Systemd and Crontab to execute scripts regularly in Linux systems
Text:
In Linux systems, we often need to execute some script tasks regularly, Such as backing up data, cleaning logs, etc. This article will introduce how to use Systemd and Crontab to implement the function of regularly executing scripts, and provide specific code examples.
1. Use Systemd to execute scripts regularly
Systemd is an initialization system and service manager under the Linux system. By creating Systemd scheduled tasks, we can easily execute scripts regularly.
cleanuplog.service
. [Unit] Description=Cleanup Log Service [Service] Type=simple ExecStart=/path/to/cleanuplog.sh [Install] WantedBy=default.target
Among them, ExecStart
specifies the script path to be executed and needs to be modified according to the actual situation. Save and close the file.
cleanuplog.timer
. [Unit] Description=Cleanup Log Timer [Timer] OnCalendar=*-*-* 01:00:00 [Install] WantedBy=timers.target
Among them, OnCalendar
specifies the trigger time of the scheduled task, which is 1 am every day. Save and close the file.
/etc/systemd/system
directory. $ sudo mv cleanuplog.service /etc/systemd/system $ sudo mv cleanuplog.timer /etc/systemd/system
$ sudo systemctl daemon-reload $ sudo systemctl enable cleanuplog.timer $ sudo systemctl start cleanuplog.timer
Now, the task of regularly executing the script has been created and started successfully.
2. Use Crontab to execute scripts regularly
Crontab is a tool for periodically executing commands or scripts. By editing the Crontab file, we can easily customize the needs for scheduled execution of scripts.
$ crontab -e
0 2 * * * /path/to/cleanuplog.sh
Among them, 0 2 * * *
represents 2 a.m. every day, /path/to/cleanuplog.sh
represents the script path to be executed, It needs to be modified according to the actual situation.
Now, the task of regularly executing the script has been added successfully.
Summary:
This article introduces how to use Systemd and Crontab to execute scripts regularly in Linux systems, and provides specific code examples. According to actual needs, choosing an appropriate method to implement scheduled tasks can improve work efficiency and automated management capabilities. I hope this article can help readers learn and apply the method of timing script execution.
The above is the detailed content of How to use Systemd and Crontab to execute scripts regularly in Linux systems. For more information, please follow other related articles on the PHP Chinese website!