java 如何让Java程序在后台运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16453082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a Java program run in the background?
提问by N01zii
I've looked at tons of different StackOverflow questions, and articles on other websites, but none of them have exactly what I'm looking for.
我查看了大量不同的 StackOverflow 问题以及其他网站上的文章,但没有一个完全符合我的要求。
What I'm attempting to do:
我正在尝试做的事情:
I have a program that needs to sleep for a while, and then check to make sure that a program is still running, then sleep again. I've gotten that part done all fine and dandy, but I'm running into a problem making it run in the background. I'm trying to get it to run with no system tray, no command prompt window, just a process. Is there any way I can do this? It really annoys me having to have a command prompt window open 24/7 for a program as simple as this one, and if anyone could help it would be great!
我有一个程序需要休眠一段时间,然后检查以确保程序仍在运行,然后再次休眠。我已经把那部分完成得很好,但我遇到了一个问题,让它在后台运行。我试图让它在没有系统托盘、没有命令提示符窗口、只有一个进程的情况下运行。有什么办法可以做到这一点吗?对于像这个这样简单的程序,必须让命令提示符窗口 24/7 全天候打开,这真的让我很恼火,如果有人能提供帮助,那就太好了!
(Also, note that I'm not talking about compiling from command line, I'm saying after you open the .exe version of the java program, how you could make it open the exe without a command prompt window or GUI)
(另外,请注意,我不是在谈论从命令行编译,我是说在您打开 java 程序的 .exe 版本后,如何让它在没有命令提示符窗口或 GUI 的情况下打开 exe)
Thanks!
谢谢!
EDIT: Yes, I am running Windows, and this program will be run solely on Windows OS'.
编辑:是的,我正在运行 Windows,并且该程序将仅在 Windows 操作系统上运行。
回答by user93353
What you want is a daemon program. The Windows equivalent of a daemon is a Windows Service.
你想要的是一个守护程序。守护进程的 Windows 等价物是 Windows 服务。
So one solution is to run your program as a Windows Service. It's very simple to convert a command line java program into a service with ProcRun. I just did this last week with a particular program I had - took around half a day, mainly because it was the first time I was doing it.
因此,一种解决方案是将您的程序作为 Windows 服务运行。使用ProcRun将命令行 java 程序转换为服务非常简单。我上周刚刚用我的一个特定程序做了这个 - 花了大约半天时间,主要是因为这是我第一次这样做。
Making it a Windows Service has the advantage that you can set it to start automatically when the machine boots.
将其设置为 Windows 服务的优点是您可以将其设置为在机器启动时自动启动。
回答by Joel
Look into javaw, which comes standard with your JRE
查看 javaw,它是 JRE 的标准配置
回答by Hot Licks
Run this VBS script from the Task Scheduler:
从任务计划程序运行此 VBS 脚本:
Set Shell = CreateObject("WScript.Shell")
Shell.CurrentDirectory = "C:\Users\myuser\mylib"
Shell.Run "java.exe MyClass", 0, False