Cron linux запуск скрипта при загрузке

Как запустить скрипт при старте ОС

В процессе использования любой операционки встает вопрос о запуске ПО по старту системы. Причем если в Windows с этим все более менее ясно, то в Linux — нет. Ибо чаще нужно не просто запустить скайп, а стартануть задачу из под root.
Раньше (когда systemd еще только угрожало) я, как и большинство народу, предпочитал просто запихать команду в /etc/rc.local.
Но вот сейчас испытал cron и понял, что несколько лет меня обманывали 😉
Cron — это служба, которая отвечает за периодические задачи. Гибкость настройки на высоте. Можно настроить выполнение по четным и не четным дням месяца, минутам/часам, дням недели.

Для настройки службы у каждого пользователя системы есть свой файл crontab.
Редактировать его можно с помощью команды

Мне нужно было запускать скрипт от root при старте ОС.

Открывается nano (не понятно почему именно он).
В конец файл добавим свою строку.

@reboot python /home/pi/MyScript.py &

Должно получиться вот так:

Осторожно с последней строкой. Она должна быть пустой. Википедия утверждает, что если это не так можно остаться без всех задач.
Ну и позволю себе содрать с вики примеры задач в crontab.

# выполнять каждый день в 0 часов 5 минут, результат складывать в log/daily 5 0 * * * $HOME/bin/daily.job >> $HOME/log/daily 2>&1 # выполнять 1 числа каждого месяца в 14 часов 15 минут 15 14 1 * * $HOME/bin/monthly # каждый рабочий день в 22:00 0 22 * * 1-5 echo "Пора домой" | mail -s "Уже 22:00" john 23 */2 * * * echo "Выполняется в 0:23, 2:23, 4:23 и т. д." 5 4 * * sun echo "Выполняется в 4:05 в воскресенье" 0 0 1 1 * echo "С новым годом!" 15 10,13 * * 1,4 echo "Эта надпись выводится в понедельник и четверг в 10:15 и 13:15" 0-59 * * * * echo "Выполняется ежеминутно" 0-59/2 * * * * echo "Выполняется по четным минутам" 1-59/2 * * * * echo "Выполняется по нечетным минутам" # каждые 5 минут */5 * * * * echo "Прошло пять минут" # каждое первое воскресенье каждого месяца. -eq 7 это код дня недели, т.е. 1 -> понедельник , 2 -> вторник и т.д. 0 1 1-7 7 * [ "$(date '+\%u')" -eq 7 ] && echo "Эта надпись выводится каждое первое воскресенье каждого месяца в 1:00"

Источник

Run Jobs or Scripts Using Crontab on Boot

Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.

Читайте также:  Linux mint экран мигает

The cron utility is a job-scheduling tool found on all Linux and Unix operating systems, as well as macOS. Although cron is typically used to schedule jobs at fixed times, dates, and intervals, it can also launch jobs at system boot time. This guide explains how to use the cron utility and the crontab file to run a job or script when the system boots.

What is the Crontab File?

Each cron job represents a command or script that automatically runs according to a predetermined schedule. The cron utility periodically scans the crontab entries and launches any job that is due to run. The cron jobs for the system are listed in the /etc/crontab file, where each line represents a different job. Every job must include a schedule, along with a command or script to run. There are different crontab files for different users, allowing jobs to be associated with an owner.

The following example demonstrates a crontab entry to run the check-routers script on an hourly basis.

The first five fields represent the minute, hour, day of the month, month, and day of the week when the job should run. The * symbol is a wildcard meaning always. So, the example job runs at the top of the hour, every hour of the day, and every day of the year.

To simplify the syntax, crontab offers shortcuts for very common schedules. For instance, the @hourly shortcut runs a job at the start of every hour. So the last example can also be entered as seen in the following example.

@hourly /opt/bin/check-routers

Similarly, the @reboot shortcut tells the cron task to run the job at system boot time.

Before You Begin

  1. If you have not already done so, create a Linode account and Compute Instance. See our Getting Started with Linode and Creating a Compute Instance guides.
  2. Follow our Setting Up and Securing a Compute Instance guide to update your system. You may also wish to set the timezone, configure your hostname, create a limited user account, and harden SSH access.

Use Crontab to Schedule a Job or Script to Run at System Startup

To schedule a job to run every time the system boots or reboots, add a new entry to the crontab file as follows.

    View all of the currently scheduled crontab entries to see whether the entry already exists.

The command sudo crontab -e opens the crontab file for the root user, while the crontab -e command opens the file for the current user. Do not add too many root-level jobs as the output can easily become overwhelming and be ignored.

Select an editor. To change later, run 'select-editor'. 1. /bin/nano  

To add a delay before running the job, prefix the string sleep && to the command. The example above would become @reboot sleep 30 && date >> ~/clock.txt .

crontab: installing new crontab 
 sudo systemctl status cron.service 
cron.service - Regular background program processing daemon Loaded: loaded (/lib/systemd/system/cron.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2021-04-22 22:10:31 UTC; 14h ago . 
 sudo systemctl enable cron.service 

Some Tips on Effectively Using the Cron Utility

  • Test any new cron entries before putting them into production. To validate a new cron entry, reboot the system and ensure the job ran correctly. To test the sample job, reboot the system and verify the system time has been added to the ~/clock.txt file. If the job is very complicated, thoroughly test all combinations and scenarios.
  • If the commands are very lengthy or complicated, consider turning them into a script. Configure the cron entry to call the script, specifying its full path, as in the following example:
 @reboot ~/util/record_start_time 

Learn More About the Cron Utility

To learn more about cron jobs, see our Schedule Tasks with Cron guide. To view highly-detailed and technical information about cron and crontab, you can also refer to the Linux ‘man’ page for the crontab command.

More Information

You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

This page was originally published on Friday, July 2, 2021.

Источник

Crontab Reboot: How to Execute a Job Automatically at Boot

The Cron daemon is a Linux utility used for scheduling system tasks and processes. It uses cron tables (crontab) to store and read scheduled jobs.

This tutorial will cover how you can use crontab to schedule jobs to be run at system reboot.

Crontab reboot: how to execute jobs automatically at boot

  • A system running Linux
  • Access to a command line/terminal window
  • A user account with root or sudo privileges

Crontab Command Overview

With the crontab command, you have full control of when and how jobs are executed. Use crontab to set job execution time down to the minute, without the need for looping and timing logic in the task.

crontab has low resource requirements since it doesn’t reserve system memory when it isn’t running.

Crontab on Boot: Run a Cron Job at Boot Time

Open the cron task list by using the following command:

If you have multiple text editors installed, the system prompts you to select an editor to update the cron task list with. Use the number in the brackets to choose your preferred option. We will be using the default option, Nano.

Opening cron jobs ist with the crontab command

Note: Leaving the field blank and pressing enter chooses the first option available.

To run a cron job at every system boot, add a string called @reboot to the end of the task list. The job defined by this string runs at startup, immediately after Linux reboots.

Use the following syntax when adding a @reboot string:

@reboot [path to command] [argument1] [argument2] … [argument n] @reboot [part to shell script]

Note: Always use the full path to the job, script, or command you want to run, starting from the root.

Press Control + X to exit Nano, then Y and Enter to save any changes you made.

For example, if we wanted to have the system date written in a file called date.txt when Linux restarts, we would add the following string:

If we wanted to run the backup shell at reboot, we would add:

Updating the cron job list

Note: In some cases, the crond service needs to be enabled on boot for the configuration to function.
To check if the crond service is enabled, use:

sudo systemctl status cron.service

To enable this service, use:

sudo systemctl enable cron.service

Run a Cron Job at Boot With Delay

To run a job with a delay after the system reboots, use the sleep command when adding the @reboot string:

@reboot sleep [time in seconds] && [path to job]

If you want to create a text file with the system date five minutes after reboot, add:

@reboot sleep 300 && date >> ~/date.txt

Remove a Reboot Command

Each @reboot string you add to the cron task list runs a job every time Linux restarts. If you no longer wish to run a job, remove it from the task list.

To do this, open the task list using the crontab -e command. Scroll down to the bottom to review the jobs you added.

To remove a task from the list, delete the appropriate line from the appropriate string. Press Control + X to exit Nano, then Y and Enter to save changes.

Note: Learn more about the Linux at command, the alternative for cron job for scheduling jobs.

After following this tutorial, you understand how to use crontab to schedule jobs to run at system reboot.

For more ways to schedule jobs in crontab, check out our guide to setting up cron jobs.

Источник

Оцените статью
Adblock
detector