Linux implementations add crontab scheduling tasks with scripts _Linux_Script Home

Linux implementations use scripts to add crontab scheduling tasks

Updated: June 18, 2024 10:51:05 Author: fangyang079
This article mainly introduces the Linux implementation with scripts to add crontab timing tasks, has a good reference value, I hope to help you, if there are mistakes or not considered completely, please feel free to advise

Linux scripts add crontab scheduling tasks

usual

The usual way to add a crontab scheduling task is to run the command manually:

crontab -e

The task script is then manually added to the file

actual

In practice, we often want to automatically add crontab scheduled tasks when executing program startup scripts, such as periodically deleting logs generated by programs through the crontab task. We can use the following script to automatically add crontab scheduled tasks through the script.

Modify the following script and execute it when the program starts.

#! /bin/sh # Log cleanup script delete_log.sh Replace it with your log cleanup script. Or refer to another blog "Cleaning Logs with Scheduled Tasks in Linux" delete_log_sh_path=/data/delete_log.sh # crontab script executes tasks at 1 am every day cron_command="0 1 * * * /bin/bash ${delete_log_sh_path} >/dev/null 2>&1" # Determining whether a scheduled task exists existing_job=$(crontab -l | grep "${delete_log_sh_path}") if [ -n "${existing_job}" ]; then echo "The cpp log scheduled clearing task already exists. Do not repeat the task!!" exit 1 fi # Add task # Output an existing task to the temporary file crontab -l > cron.txt # append a new task to the end of the file echo "${cron_command}" >> cron.txt # Load the scheduled task crontab txt # Delete a temporary file rm -f cron.txt crontab -l echo "The cpp log scheduled clearing task has been created" exit 0

Linux crontab scheduling task Chinese characters are garbled

Problem phenomenon

The script is executed without garbled characters. After a scheduled task is executed, the script becomes?? .

Problems caused by the original

The crontab task does not obtain system environment variables, causing garbled characters in Chinese

solution

Add the encoding method or add the corresponding environment variable in the execution step

Such as:

1. Add at the beginning of the script:

#! /bin/bash . /etc/profile . ~/.bash_profile export LANG="en_US.UTF-8"

2. /usr/bin/java -Dfile.encoding=UTF-8 -jar ALDTool.jar

Sum up

The above is personal experience, I hope to give you a reference, but also hope that you support the script home.

Related article

Latest comments