You really want to use at
. It is exactly made for this purpose.
echo /usr/bin/the_command options | at now + 1 day
However if you don't have at
, or your hosting company doesn't provide access to it, you can have a cron job include code that makes sure it only runs once.
Set up a cron entry with a very specific time:
0 0 2 12 * /home/adm/bin/the_command options
Next /home/adm/bin/the_command needs to either make sure it only runs once.
#! /bin/bash
COMMAND=/home/adm/bin/the_command
DONEYET="${COMMAND}.alreadyrun"
export PATH=/usr/bin:$PATH
if [[ -f $DONEYET ]]; then
exit 1
fi
touch "$DONEYET"
# Put the command you want to run exactly once here:
echo 'You will only get this once!' | mail -s 'Greetings!' [email protected]
You could put a crontab file in /etc/cron.d
which would run a script that would run your command and then delete the crontab file in /etc/cron.d
. Of course, that means your script would need to run as root.
For those who is not able to access/install at
in environment, can use custom script:
#!/bin/bash
if [ $# -lt 2 ]; then
echo ""
echo "Syntax Error!"
echo "Usage: $0 <shell script> <datetime>"
echo "<datetime> format: %Y%m%d%H%M"
echo "Example: $0 /home/user/scripts/server_backup.sh 202008142350"
echo ""
exit 1
fi
while true; do
t=$(date +%Y%m%d%H%M);
if [ $t -eq $2 ]; then
/bin/bash $1
echo DONE $(date);
break;
fi;
sleep 1;
done
Let's name the script as run1time.sh Example could be something like:
nohup bash run1time.sh /path/to/your/script.sh 202008150300 &
at
is the correct way.
If you don't have the at
command in the machine and you also don't have install privilegies on it, you can put something like this on cron
(maybe with the crontab
command):
* * * 5 * /path/to/comand_to_execute; /usr/bin/crontab -l | /usr/bin/grep -iv command_to_execute | /usr/bin/crontab -
it will execute your command one time and remove it from cron
after that.
Your comment suggests you're trying to call this from a programming language. If that's the case, can your program fork a child process that calls sleep then does the work?
What about having your program calculate the number of seconds until the desired runtime, and have it call shell_exec("sleep ${secondsToWait) ; myCommandToRun");
You really want to use at. It is exactly made for this purpose.
echo /usr/bin/the_command options | at now + 1 day
However if you don't have at, or your hosting company doesn't provide access to it, you could make a self-deleting cron entry.
Sadly, this will remove all your cron entries. However, if you only have one, this is fine.
0 0 2 12 * crontab -r ; /home/adm/bin/the_command options
The command crontab -r
removes your crontab entry. Luckily the rest of the command line will still execute.
WARNING: This is dangerous! It removes ALL cron entries. If you have many, this will remove them all, not just the one that has the "crontab -r" line!
Source: Stackoverflow.com