启动带有定时任务调度的JAR文件在Linux后台运行

huangapple go评论78阅读模式
英文:

Start jar file with TimerTask schedule in background in linux

问题

我正在尝试在后台运行我的应用程序的JAR文件。我已经尝试过nohup和&,但它们不起作用。

nohup java -cp ~/DataGenerator/target/GenerateDataApp-1.0-SNAPSHOT.jar Generator.App -p ~/Text2.txt &

我的应用程序是一个简单的定时器,每1秒运行一次,在每次运行时生成一个随机数并将其保存到文件中。

public class App {
    public static void main(String[] args) throws Exception{
        System.out.println("Start");
        Arguments arguments = Arguments.fromMain(args);
        SaveToFile saveToFile = new SaveToFile();
        saveToFile.creatFile(arguments.getPathToPropertiesFile());
        Timer timer = new Timer();
        timer.schedule(new SaveFileRunner(arguments), 0, 100);
    }
}

我还尝试过Bash脚本,但也没有帮助。

#!/bin/sh
cd ~/DataGenerator/target
java -cp ~/DataGenerator/target/GenerateDataApp-1.0-SNAPSHOT.jar Generator.App -p ~/Text.txt

有人可以建议我如何使定时器在后台工作吗?

英文:

I am trying to run my application from a jar file in background. I've already tried nohup and & but they don't work.

nohup java -cp ~/DataGenerator/target/GenerateDataApp-1.0-SNAPSHOT.jar Generator.App -p ~/Text2.txt &

My application is a simple timer that runs every 1s, generating a random number every time and saving it to a file.

public class App {
    public static void main(String[] args) throws Exception{
        System.out.println("Start");
        Arguments arguments = Arguments.fromMain(args);
        SaveToFile saveToFile = new SaveToFile();
        saveToFile.creatFile(arguments.getPathToPropertiesFile());
        Timer timer = new Timer();
        timer.schedule(new SaveFileRunner(arguments), 0, 100);
        

    }
}

I also tried the bash script, but it didn't help either.

#!/bin/sh
cd ~/DataGenerator/target
java -cp ~/DataGenerator/target/GenerateDataApp-1.0-SNAPSHOT.jar Generator.App -p ~/Text.txt

Could someone advise me how can I make a timer work in the backend?

答案1

得分: 1

要使程序作为后台作业运行,请在命令行的末尾添加&。例如:

java ...在这里添加参数... &

这样做的一个可能问题是,如果程序输出内容,它仍然会显示在终端上。您可以将该输出发送到一个文件中。

java ...在这里添加参数... >output.txt 2>&1 &

第二个问题是,如果您关闭终端或注销,程序会停止运行。为了避免这种情况,请使用nohup

nohup java ...在这里添加参数... >output.txt 2>&1 &

英文:

To make a program run as a background job, add & to the end of the command line. For example:

java ...parameters here... &

A possible problem with this is if the program writes output, that is still displayed in the terminal. You can send that output to a file.

java ...parameters here... >output.txt 2>&1 &

A second problem is that if you close the shell or logout, the program is stopped. To avoid that, use nohup.

nohup java ...parameters here... >output.txt 2>&1 &

huangapple
  • 本文由 发表于 2020年8月4日 00:41:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63233493.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定