将 Java 控制台应用程序作为守护进程运行(后台)
我开发了一个Java控制台应用程序,当启动时,打开一个控制台窗口并保持在前台,我想在后台启动该应用程序。
现在我通过此命令行启动应用程序:
java -jar myapp.jar
有没有办法实现此行为? 更改命令行参数就足够了,还是我需要对我的代码进行一些更改?
I've developed a Java console application that when start, open a console window and remain in foreground, i want to start that application in background .
Now i launch the application by this command line :
java -jar myapp.jar
Is there a way to achieve this behaviour ?
It's enough change the command line parameter or i need to do some change on my code ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
答案取决于操作系统。
The answer is operating system dependent.
如果您在任何基于 UNIX 的系统中执行此操作,那么您可以附加 &到最后将产生一个新线程并使其在后台运行。
If you are doing this in anything unix based then you can append & to the end which will spawn a new thread and keept it running in the background.
如果您确实只想让它在后台运行,
java -jar myapp.jar &
就可以完成这项工作。这样,当 shell 关闭时它仍然会死掉,但你可以继续使用你的 shell。如果您确实希望它作为守护程序运行,则 nohup java -jar myapp.jar & 即可完成这项工作。这样,当外壳关闭时,它会继续存活。
如果您希望它可靠,您可以准备一个 init 脚本或 upstart 作业定义,或者通过 Vixie
cron(8)
@reboot
说明符运行它,使其在启动时启动。If you really just want it to run in the background,
java -jar myapp.jar &
will do the job. That way, it'll still die when the shell closes, but you can keep using your shell.If you really want it run as a daemon,
nohup java -jar myapp.jar &
will do the job. That way, it'll continue to live when the shell closes.If you want this to be reliable, you can prepare an init script or upstart job definition, or run it via Vixie
cron(8)
@reboot
specifier to make it start at boot.鉴于您使用的是 Windows,您可能会考虑 Java Service Wrapper。我过去在一个项目中使用过它。
Given that you're using Windows, you might consider Java Service Wrapper. I have used it on a project in the past.