In Linux, is there a way to run a cron job in the foreground (or interactive mode)? (I have a program that runs periodically to accept user input and do some processing. So I want to schedule it as a cron job that can run in the foreground).
4 Answers
Try this out on your user's crontab
:
@hourly DISPLAY=:0 xterm -e /path/to/my/script.sh
It will open (hourly) an xterm
with your script executing, and exit after your script exits. Of course, you should modify the @hourly
part to suit your needs.
For GUI
scripts in cron
, try the following line in a shell
:
crontab -e
Then in crontab
:
0 7 * * * DISPLAY=:0 /PATH/TO/SCRIPT
-
-
I tried the same but it still seems to run in the background. Thanks for your answer anyway.– NeoOct 7, 2012 at 18:28
-
It worked for me, although I had to restart cron through service cron restart :) Dec 11, 2019 at 12:36
Assuming you are running X, you could always have it open a window on a selected display.
-
I am assuming, you mean Mac OS X. I am using Ubuntu. However, I would want my script to work on Ubuntu as well as Mac OS X.– NeoOct 7, 2012 at 18:10
-
3I meant X windows, en.wikipedia.org/wiki/X_Window_System, and you are probably using it– OfirOct 7, 2012 at 18:12
-
-
You should export display variable or add that into your bashrc file– anlgrsesAug 7, 2020 at 21:34
If you don't have a GUI and you only have the terminal, divert the exit to tty. Execute ´tty´ and it will return the device to which you will redirect the output. For example, in Centos it will be something like:
/ dev / pts / 0
Then in crontab -e
you write:
1 * * * * user sh / PATH / TO / SCRIPT> / dev / pts / 0
Adjust the time in crontab according to your needs. It will only run if there is someone with that terminal open.
BUT WHAT PEOPLE ARE LOOKING FOR BY THE TITLE OF THE QUESTION:
Linux: Run cron job in foreground
The answer is nohup command_to_run &
:
1 * * * * nohup user sh / PATH / TO / SCRIPT &
nohup
allows executing a script as if it were an open terminal and solves the problem of executing the crontab. I mean when we create a script, for example:
#! / bin / bash
echo "I make it up"
And we wait for the output of the echo to do something with it. Example:
echo "I make it up"
if [[$? -gt 0]]
then
do something with the output of echo
The echo
execution response is obtained through stdout
in the tty terminal. But from crontab "there is no tty" and a crash occurs and crontab does not execute the application. This is solved with nohup
. More information: man nohup
cron
to reach out to you? Opening a terminal, launching a GUI app etc?expect
tcl.tk/man/expect5.31/expect.1.html but I am not sure it is a good idea to use it.