Problem: Running a Cron Job Once at a Specific Time
Cron jobs are usually set up to run repeatedly at scheduled times. However, sometimes you need to run a task only once at a specific time. This can be tricky when setting up cron to perform a single, time-specific task without repeating it.
Solutions for Running Cron Jobs Once at a Specific Time
Using the 'at' Command for One-Time Scheduling
The 'at' command schedules one-time tasks. You can set a future time for a command to run. The syntax is:
echo "/path/to/command options" | at [time]
To run a command tomorrow:
echo "/usr/bin/my_command" | at now + 1 day
Tip: Verify Scheduled Tasks
Use the 'atq' command to list all scheduled tasks. This helps you confirm that your task was successfully scheduled and view its queue number for potential modifications or deletions.
Cron Job with Self-Disabling Script
If 'at' is not available, create a self-disabling script:
-
Set up a cron job with a specific time:
0 0 2 12 * /path/to/your_script.sh
-
Create a script that runs only once:
#!/bin/bash SCRIPT="/path/to/your_script.sh" MARKER="${SCRIPT}.done" if [ -f "$MARKER" ]; then exit 0 fi # Your one-time task here echo "Task executed" | mail -s "One-time task complete" user@example.com touch "$MARKER"
This script checks for a marker file and exits if it exists, stopping multiple runs.
Using Cron with Date Checking
Another method uses date checking:
#!/bin/bash
EXECUTION_DATE="2023-12-25"
CURRENT_DATE=$(date +%Y-%m-%d)
if [ "$CURRENT_DATE" != "$EXECUTION_DATE" ]; then
exit 0
fi
# Your one-time task here
echo "Holiday task executed" | mail -s "Holiday task complete" user@example.com
This script runs the task only on the set date, exiting if the current date doesn't match.
Example: Adding Logging to Date-Based Cron Jobs
#!/bin/bash
EXECUTION_DATE="2023-12-25"
CURRENT_DATE=$(date +%Y-%m-%d)
LOG_FILE="/var/log/one_time_cron.log"
if [ "$CURRENT_DATE" != "$EXECUTION_DATE" ]; then
echo "$(date): Script checked, but not executed (wrong date)" >> "$LOG_FILE"
exit 0
fi
# Your one-time task here
echo "Holiday task executed" | mail -s "Holiday task complete" user@example.com
echo "$(date): Task executed successfully" >> "$LOG_FILE"
This example adds logging to track script execution attempts and successes, which is useful for monitoring and troubleshooting one-time cron jobs.