Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
Next revisionBoth sides next revision
docs:guide-user:base-system:cron [2019/03/19 16:27] – [Periodically check of internet and reboot if needed] use community site vgaeteradocs:guide-user:base-system:cron [2023/08/08 11:30] – Added my cronjob to keep last N snapshots of config torxgewinde
Line 1: Line 1:
-====== Cron and crontab ======+====== Scheduling tasks with cron ====== 
 +{{section>meta:infobox:howto_links#basic_skills&noheader&nofooter&noeditbutton}}
  
-[[wp>Cron]] allows to run jobs (programs, scripts) at specified times.+===== Introduction ===== 
 +  * OpenWrt can run scheduled tasks using [[wp>Cron|cron]] service. 
 +  * This how-to describes the method for setting up cron jobs
 +  * See also [[docs:guide-user:advanced:watchcat|Watchcat]] to reboot based on schedule or connectivity.
  
-OpenWrt comes with cron system by default, provided by busybox.+===== Goals ===== 
 +  * Run programs or scripts at specific time. 
 +  * Automate scheduled task management.
  
-===== Adding and editing cron jobs =====+===== Web interface instructions ===== 
 +Set up cron jobs using web interface. 
 +  - Navigate to **LuCI -> System -> Scheduled Tasks**. 
 +  - Edit the configuration and click the **Save** button. 
 + 
 +===== Command-line instructions ===== 
 +Set up cron jobs using command-line interface.
  
-You can edit the current config with: 
 <code bash>  <code bash> 
 +# Edit configuration
 crontab -e  crontab -e 
 +
 +# Show configuration
 +crontab -l
 +
 +# Apply changes
 +/etc/init.d/cron restart
 </code> </code>
  
-:!There should be a end-of-line character on the last line of the crontab file If in doubt, just leave an empty line at the end.+This will edit the configuraion ''/etc/crontabs/root'' file in [[docs:guide-user:base-system:user.beginner.cli#editing_files|vi editor]].
  
-Example of time specification: +:!There should be a EOL character on the last line of the crontab file
-  +Just leave an empty line at the end to be sure.
-^  min\\ 0-59  ^  hour\\ 0-23  ^  day/month\\ 1-31  ^  month\\ 1-12  ^  day/week\\ 0-6  ^ Description +
-|   */     *        *    |      |     | every 5 minutes +
-|   12    |   */ |      *    |      |     | every 3 hours at 12 minutes +
-|   57    |   11       15    | 1,6,12 |     | At 11:57 Hrs  on 15th of Jan, June & Dec | +
-|   25    |    6        *    |    *    1-5  | At 6:25 AM every weekday (Mon-Fri) +
-|          0    4,12,26  |    *       | At midnight on 4th, 12th and 26th of every month  | +
-|  5,10    9,14  |    10        *    0,4  | At 9:05AM, 9:10AM, 2:05PM and 2:10PM every Sunday and Thursday  |+
  
-<WRAP left round tip 70%> +===== Task specification ===== 
-0 (zero) is treated as Sunday. If you set the day of the week to 7, busybox will go bonkers and run your command every day. +Each line is a separate task written in the specification:
-</WRAP> +
-===== Activating cron =====+
  
-Cron is not enabled by default, so your jobs won't be run.  To activate cron: +<code> 
- +* * * * * command to execute 
-<code bash+- - - - - 
-/etc/init.d/cron start +| | | | | 
-/etc/init.d/cron enable+| | | | ----- Day of week (0 - 6) (Sunday =0) 
 +| | | ------- Month (1 - 12) 
 +| | --------- Day (1 - 31) 
 +| ----------- Hour (0 - 23) 
 +------------- Minute (0 - 59)
 </code> </code>
  
-:!: If there is no crontab defined (i.e. ''/etc/crontabs/'' is empty), then cron won't start!  Make sure you already defined cron jobs before trying to start cron.+Examples of time specification:
  
-===== References =====+^  min\\ 0-59  ^  hour\\ 0-23  ^  day/month\\ 1-31  ^  month\\ 1-12  ^  day/week\\ 0-6  ^ Description ^ 
 +|  */5  |  *  |  *  |  *  |  *  | Every 5 minutes | 
 +|  12  |  */3  |  *  |  *  |  *  | Every 3 hours at 12 minutes | 
 +|  57  |  11  |  15  | 1,6,12 |  *  | At 11:57 Hrs on 15th of Jan, June & Dec | 
 +|  25  |  6  |  *  |  *  |  1-5  | At 6:25 AM every weekday (Mon-Fri) | 
 +|  0  |  0  |  4,12,26  |  *  |  *  | At midnight on 4th, 12th and 26th of every month | 
 +|  5,10  |  9,14  |  10  |  *  |  0,4  | At 9:05AM, 9:10AM, 2:05PM and 2:10PM every Sunday and Thursday |
  
-  * [[http://linux.die.net/man/5/crontab|crontab manpage]] +:!0 (zero) is treated as Sunday
-  * [[http://adminschoice.com/crontab-quick-reference]] +If you set the day of the week to 7, BusyBox will go bonkers and run your command every day.
-  * see [[http://www.busybox.net/downloads/BusyBox.html]] for options of the Busybox implementation+
  
-===== Tips and tricks =====+**Table of shortcuts:**
  
-==== Check that the jobs are run ====+^ Shortcut ^ Equivalent ^ Description ^ 
 +| ''@yearly'' | ''0 0 1 1 *'' | Every year | 
 +| ''@annually'' | ''0 0 1 1 *'' | Every year | 
 +| ''@monthly'' | ''0 0 1 * *'' | Every month | 
 +| ''@weekly'' | ''0 0 * * 0'' | Every week | 
 +| ''@daily'' | ''0 0 * * *'' | Every day | 
 +| ''@midnight'' | ''0 0 * * *'' | Every day | 
 +| ''@hourly'' | ''0 * * * *'' | Every hour |
  
-Each time a job is run by cron, a line is printed in OpenWrt logs.  Run ''logread'' to check whether your jobs are correctly run.+:!:  Time shortcuts are not enabled by default. Shortcuts require compiling busybox with FEATURE_CROND_SPECIAL_TIMES enabled in the busybox compile options.
  
-==== Periodic reboot of a router ====+===== Troubleshooting ===== 
 +You can read log messages with:
  
-A simple solution for some hard-to-solve problems (memory leak, performance degradation, ...) is to reboot the router periodically, for instance every night.+<code bash> 
 +logread -e cron 
 +</code>
  
-Howeverthis is not as simple as it seems, because the router usually does not have a real-time clock.  This could lead to a never-ending loop of reboots.+Not all messages are loggedto increase logging change ''[[docs:guide-user:base-system:system_configuration|cronloglevel]]'' option.
  
-In the boot process the clock is initially set by ''sysfixtime'' to the most recent timestamp of any file found in /etcThe most recent file is possibly a status file or config file, modified maybe 30 seconds before the reboot initiated by cronSo, in the boot process the clock gets set backwards a few seconds to that file's timestampThen cron starts and notices a few seconds later that the required boot moment has again arrived and reboots again... (At the end of the boot process ntpd starts, and it may also take a while before ntpd gets and sets the correct time, so cron may start the reboot in between.)+===== Extras ===== 
 +==== References ==== 
 +  * [[man>crontab(1)]], [[man>crontab(5)]] 
 +  * [[https://busybox.net/downloads/BusyBox.html#crontab|BusyBox crontab]] 
 +  * [[http://adminschoice.com/crontab-quick-reference|Crontab quick reference]]
  
-One solution for cron is to use a delay and touch a file in /etc before reboot:+==== Periodic reboot ==== 
 +A simple workaround for some hard-to-solve problems (memory leak, performance degradation, ...) is to reboot the router periodically, for instance every night. 
 + 
 +However, this is not as simple as it seems, because the router usually does not have a real-time clock. 
 +This could lead to a never-ending loop of reboots. 
 + 
 +In the boot process the clock is initially set by ''sysfixtime'' to the most recent timestamp of any file found in /etc. 
 +The most recent file is possibly a status file or config file, modified maybe 30 seconds before the reboot initiated by cron. 
 +So, in the boot process the clock gets set backwards a few seconds to that file's timestamp. 
 +Then cron starts and notices a few seconds later that the required boot moment has again arrived and reboots again... 
 +At the end of the boot process ntpd starts, and it may also take a while before ntpd gets and sets the correct time, so cron may start the reboot in between. 
 + 
 +One solution for cron is to use a delay and touch a file in ''/etc'' before reboot.
  
 <code bash> <code bash>
Line 68: Line 112:
 </code> </code>
  
-:!: On many platforms ''shutdown'' does not work; it will just halt the CPU but it won't power off the device. There is usually no programmable circuitry to actually power off the unit. ''reboot'' does work, in case you should want to reboot the router periodically.+:!: On many platforms ''shutdown'' does not work; it will just halt the CPU but it won't power off the device. 
 +There is usually no programmable circuitry to actually power off the unit. 
 +''reboot'' does work, in case you should want to reboot the router periodically.
  
-==== Periodically check of internet and reboot if needed ==== +==== Periodic network restart ==== 
- +A simple solution for restart all your network (lanwan and wifi) every 10 minutes is this:
-Sometimes router can works during days (even months), and then suddenly connection to the internet disappears. But router is working and we need just reboot it using web-interface. +
- +
-In this case we can periodically check of the internet and reboot if needed. +
- +
-**Solution:** +
- +
-Create bash script to ping some site and reboot the router if needed.+
  
 <code bash> <code bash>
-cat << "EOF"/root/pingRouterCheckReboot.sh +*/10 * * * * /etc/init.d/network restart 
-#!/bin/sh+</code>
  
-# Prepare vars +==== Alarm clock ==== 
-DATE=$(date +%Y-%m-%d" "%H:%M:%S) +If you have [[wp>Daylight saving time|DST]] you could write yourself a nice alarm clock. 
-logFile="/root/pingRouterCheckReboot.log" +When DST starts in central Europe, clocks advance from 02:00 CET to 03:00 CEST on last Sunday in March. 
 +Six day before that, you could make your WoL wake you 10 minutes earlier. 
 +Later won't work, you'll be late. 
 +When DST ends in central Europe, clocks retreat from 03:00 CEST to 02:00 CET on last Sunday in October.
  
-# Ping and reboot if need 
-ping -c3 openwrt.org 
- 
-if [ $? -eq 0 ]; then 
-    echo "ok"  
-    echo "${DATE} - ok" >> $logFile 
-else 
-    echo "REBOOT"  
-    echo "${DATE} - REBOOT" >> $logFile 
-    reboot 
-fi 
- 
-# If the log file size is greater then 100KB (102400 bytes), then renew it. 
-logFileSize=$(wc -c "$logFile" | awk '{print $1}') 
-if [ $logFileSize -gt 102400 ]; then 
-    echo "Size of $logFile = $logFileSize bytes."  
-    echo "Renew the log file"  
- 
-    mv -f $logFile "${logFile}.bk"  
-fi 
-EOF 
- 
-chmod +x /root/pingRouterCheckReboot.sh 
-</code> 
- 
-Add cron task to run this script every 15 minutes: 
 <code bash> <code bash>
-Check every 15 minutes ping to google.com +min hour day month dayofweek command 
-# If it is failed, then reboot the router +59 05 * * /usr/bin/wol -h 192.168.1.255 xx:xx:xx:xx:xx:xx 
-# Note: To avoid infinite reboot loop, wait 70 seconds and touch a file in /etc  +# crontab must end with the last line as space or a comment
-# so clock will be set properly on reboot before cron starts. +
-0,15,30,45 * * * * sleep 70 && touch /etc/banner && /root/pingRouterCheckReboot.sh+
 </code> </code>
  
-The logs will be in ''/root/pingRouterCheckReboot.log''+==== Keep number of configs / snapshots of config ==== 
-==== Alarm clock ==== +To keep number N of configurations/settings at the directory "/root"you can also use cronThis way you can access and restore configurations of the past 100 daysThe cronjob can easily be extended to copy the config to another deviceto be able to replicate a broken OpenWRT device from scratch.
- +
-If you have [[wp>Daylight saving time]] you could write yourself nice alarm clock ;-) +
-When DST starts in central Europeclocks advance from 02:00 CET to 03:00 CEST on last Sunday in March. +
-Six day before that, you could make your WOL wake you 10 minutes earlierLater won't workyou'll be late ;-) +
-When DST ends in central Europe, clocks retreat from 03:00 CEST to 02:00 CET on last Sunday in October.+
  
 <code bash> <code bash>
-#min hour day month dayofweek command +#Make a new backup/configurations snapshot at nighttime 00:01 am, keep last N=100 snapshots 
-59 05 * * 1 /usr/bin/wol -h 192.168.1.255 xx:xx:xx:xx:xx:xx Mo +#01 00 * * * sysupgrade -b "/root/backup-${HOSTNAME}.tar.gz" <-- keep just one config 
-#crontab must (as fstabend with the last line as space or a comment+01 00 * * * find "/root" -type f -name "backup-*.tar.gz" | sort -r | awk 'NR > 100' | xargs rm -f; sysupgrade -b "/root/backup-${HOSTNAME}-$(date +\%Y-\%m-\%d-\%H-\%M-\%S).tar.gz"
 </code> </code>
  
  • Last modified: 2023/10/14 06:55
  • by vgaetera