在特定时间运行Java程序
我需要帮助在特定时间(例如下午 2 点)在服务器上运行我的 Java 程序(以索引新文件)。
有人告诉我 Java 有一种叫做工作的东西,但我不知道如何使用它。我尝试了这个:
boolean cond=true;
while(cond){
@SuppressWarnings("deprecation")
int heur = new Date().getHours();
@SuppressWarnings("deprecation")
int minute= new Date().getMinutes();
if(heur==16 && minute==02){
indexer.close();
end = new Date().getTime();
File f;
cond=false;
}
但是程序仍然在运行。
如何在指定时间运行我的程序?
i need help to run my Java program on the server at a specific time like 2 pm (to index the new files).
Someone told me that Java has some thing called jobs but I don't know how to work with that. I tried this:
boolean cond=true;
while(cond){
@SuppressWarnings("deprecation")
int heur = new Date().getHours();
@SuppressWarnings("deprecation")
int minute= new Date().getMinutes();
if(heur==16 && minute==02){
indexer.close();
end = new Date().getTime();
File f;
cond=false;
}
But with this the program is still running.
How could I run my program at a specified time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一个名为 Quartz 的 API,您的程序可以在其中安排“作业”并在该处运行它时间。
在我给出示例之前,请尝试此链接。
编辑:
首先,您必须创建一个实现 org.quartz.Job 的类。当您实现该方法时,您必须实现方法
execute(JobExecutionContext jobExecution)
,该方法将在“触发器”被触发时运行。要设置时间表:
Theres a API called Quartz, It's where your program can schedule "Jobs" and it will run it at that time.
Until I can give an example, try this link.
Edit:
First you have to create a class that implements org.quartz.Job. When you implement that you will have to implement the method
execute(JobExecutionContext jobExecution)
, which is the method that will run when the "trigger" is fired.To set up the Schedule:
循环中没有 Thread.sleep() 调用,因此它会以 100% CPU 的速度“旋转”(不好),但无论如何,这是一个糟糕的设计。一个很大的改进是简单地计算“现在”和您希望它运行之间的毫秒数,然后调用 Thread.sleep(n)。
然而,更好的解决方案是使用 JDK 已经提供的解决方案。
看一下这段代码,它使用 JDK 并发库中的类。
这是一个非常简单的例子,可以工作:
There's no
Thread.sleep()
call in the loop, so it will "spin" at 100% CPU (not good), but it's a poor design anyway. A big improvement would be to simply calculate the number of milliseconds between "now" and when you want it to run, then call Thread.sleep(n).However, a better solution is to use what the JDK already provides.
Have a look at this code which uses classes from the JDK concurrent library.
This is a very simple example that would work: