简体   繁体   English

Linux:在前台运行 cron 作业

[英]Linux: Run cron job in foreground

In Linux, is there a way to run a cron job in the foreground (or interactive mode)? Linux,有没有办法在前台(或交互模式)运行cron作业? (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). (我有一个定期运行的程序来接受用户输入并进行一些处理。所以我想将它安排为可以在前台运行的 cron 作业)。

Try this out on your user's crontab : 在用户的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. 它将在您的脚本执行时打开(每小时)一个xterm ,并在脚本退出后退出。 Of course, you should modify the @hourly part to suit your needs. 当然,您应该修改@hourly部分以满足您的需求。

For GUI scripts in cron , try the following line in a shell : 对于cron GUI脚本,请在shell尝试以下行:

crontab -e

Then in crontab : 然后在crontab

0 7 * * * DISPLAY=:0 /PATH/TO/SCRIPT

假设您正在运行X,您可以随时在所选显示器上打开一个窗口。

If you don't have a GUI and you only have the terminal, divert the exit to tty.如果您没有 GUI 而您只有终端,请将出口转移到 tty。 Execute ´tty´ and it will return the device to which you will redirect the output.执行“tty”,它将返回您将输出重定向到的设备。 For example, in Centos it will be something like:例如,在 Centos 中,它将类似于:

/ dev / pts / 0 

Then in crontab -e you write:然后在crontab -e你写:

1 * * * * user sh / PATH / TO / SCRIPT> / dev / pts / 0

Adjust the time in crontab according to your needs.根据您的需要调整 crontab 中的时间。 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 Linux:在前台运行 cron 作业

The answer is nohup command_to_run & :答案是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. nohup允许像打开终端一样执行脚本,并解决了执行 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.我们等待 echo 的输出对其进行处理。 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. echo执行响应是通过 tty 终端中的stdout获得的。 But from crontab "there is no tty" and a crash occurs and crontab does not execute the application.但是从 crontab 中“没有 tty”并且发生崩溃并且 crontab 不执行应用程序。 This is solved with nohup .这可以通过nohup解决。 More information: man nohup更多信息: man nohup

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM