Linux后台运行程序



命令

nohup java Demo &   //&表示后台运行



实例:

我这里写了一个每秒将一个时间写到本地a.txt文件下的Demo

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Demo {

    public static void main(String[] args) {
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new FileOutputStream("a.txt",true));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        while(true){
            try {
                Thread.sleep(1000);
                SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String date = sd.format(new Date());
                pw.println(date);
                pw.flush();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}



现在我要将它设置为后台运行

nohup java Demo &



出现这个提示说明已经成功了,回车可以继续操作

1




使用tail –f a.txt 查看是否有数据输出

2




使用 jobs 可以查看任务



Running表示正在运行

3




使用 fg %n 可以关闭任务



输入之后按 ctrl+c 即可退出

4




Linux开机自启动Java后台任务


在文件/etc/rc.d/rc.local中添加如下内容

export JAVA_HOME=/home/jdk1.8.0_60
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
nohup java Demo &



重启之后就变成开机自启动的后台任务了

Logo

更多推荐