Monday, April 29, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 4324  / 3 Years ago, thu, may 6, 2021, 3:48:03

I want to run a cronjob daily at a specific time range but only once in that period.
How is that possible?



I see a possibility in anacrhon but don't know how to set up such scenario.


More From » cron

 Answers
2

You can place you cronjob in /etc/cron.daily/ and it will automatically run in that timeframe.




Edit:


Sorry, I was referencing an old Debian installation where anacron wasn't installed by default. In that case /etc/cron.daily/ was executed by /etc/crontab on 6:25. But newer Debian installations (and so does Ubuntu) install anacron by default and so /etc/cron.daily/ will be executed by /etc/anacrontab five minutes after anacron was started or every new day.




To achieve your schedule (from the comments) you can set up a cronjob that will e.g. every 10 min between 3-6 start either anacron that will take care that the backup job only run once or you can write a custom controll script.


1. Alternative: anacron


mkdir ~/.local/share/anacron_spool
echo "1 0 backup.daily /path/to/backup.sh" > ~/.config/anacrontab
(crontab -l; echo "*/10 3-6 * * * /usr/sbin/anacron -s -t $HOME/.config/anacrontab -S $HOME/.local/share/anacron_spool") | crontab -

This will make anacron to serialize (-s) run all jobs defined in ~/.config/anacrontab. Because by default only root has write permission to write to /var/spool/anacron/ where the timestamps are stored we use a custom spool-dir (-S). If all jobs are done for today anacron will exit.


2. Alternative: custom controll script


Open an editor (e.g. sudo nano /usr/local/bin/run_once_a_day.sh) and paste this:


#!/bin/bash
SPOOL="$HOME/.local/share/run_once_spool/"
if [ $# != 2 ]; then
echo "Usage: $(basename $0) <job-identifier> <command>"
exit 1
fi

if [ ! -d $SPOOL ]; then
mkdir $SPOOL
fi

if [ -e ${SPOOL}${1} ]; then
last_run=$(cat ${SPOOL}${1})
else
last_run=0
fi

today=$(date +%Y%m%d)
if [ $last_run != $today ]; then
$2
echo $today > ${SPOOL}${1}
fi

Press CTRL+O to save and CTRL+X to exit. Make it executeable and add a cronjob that will start it periodicaly with:


sudo chmod 755 !$
(crontab -l; echo "*/10 3-6 * * * /usr/local/bin/run_once_a_day.sh backup.daily /path/to/backup.sh") | crontab -

[#29875] Friday, May 7, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bleger

Total Points: 468
Total Questions: 108
Total Answers: 100

Location: Belarus
Member since Wed, Dec 7, 2022
1 Year ago
;