To run a cron job at midnight, you would prefix your command or the path to your script with:
0 0 * * *
For example, to run /home/youssif/myscript
, you would use:
0 0 * * /home/youssif/myscript
in your crontab file.
To edit your crontab file, use crontab -e
to run the command as your current user. Alternatively, if you absolutely need to run the command as root, you can run sudo crontab -e
to edit your crontab file.
To run the command in a terminal (not a good idea if you run the command as root), you will need to specify the display to use in your command or in your script. To do this, assuming your $DISPLAY
is :0
(default) you can prefix your command with the following variable:
DISPLAY=:0
Also, a terminal will typically close after the command is executed but you can use the hold option with xterm to keep the terminal open.
So, to run echo "hello world"
in a terminal at midnight, your command would look like this:
0 0 * * DISPLAY=:0 xterm -hold -e 'echo "hello world"'
or to run your script:
0 0 * * DISPLAY=:0 xterm -hold -e '/home/youssif/myscript'
However, the standard way to inspect the output of a cronjob is to redirect the terminal output to a file which you can look at later.
For example, to redirect the terminal output to the file /home/youssif/helloworld.log
you would use the following line in your crontab file:
0 0 * * echo "hello world" > /home/youssif/helloworld.log
Alternatively, you can also use the tee
command to redirect the output like this:
0 0 * * echo "hello world" | tee /home/youssif/helloworld.log
Finally, you can use the cat
command to view the contents of the file:
cat /home/youssif/helloworld.log
This way, the command can run in the background but you can still inspect the output.
To disable/enable tasks based on the result of an already run task, I think this would really be more appropriate for a separate question. I believe your answer would involve using an "if then else" statement in a bash script.
EDIT:
As @Tcooper pointed out, we have to add 2>&1
to redirect all the output, including error messages so you might want to use something like this instead:
0 0 * * echo "hello world" 2>&1 > /home/youssif/helloworld.log
or
0 0 * * echo "hello world" 2>&1 | tee /home/youssif/helloworld.log