简体   繁体   English

安排Java中的任务每隔X天运行一次或仅执行一次

[英]Scheduling a task in Java to run every X days or execute once only

Both a stackoverflow and a Java beginner here. 这里既有stackoverflow也有Java初学者。

So I'm trying to implement a scheduler into my app. 所以我试图在我的应用程序中实现一个调度程序。 I want a certain process / job to run every X amount of time or to run just once. 我希望某个进程/作业每X时间运行一次或仅运行一次。 This time needs to be configurable, so I made a simple Schedule object with fields like startDate , lastExecuted , an enum for the frequency and getters, and setters. 这次需要配置,因此我制作了一个简单的Schedule对象,其中包含startDatelastExecuted ,频率和获取器以及设置器的枚举之类的字段。

Now, it is easy to make it execute a task every X days for example - I just used Groovy's TimeCategory and made a thread which constantly runs and checks if the time between the lastExecuted and the current time is more than the time specified in the frequency enum of the Schedule 现在,很容易使它每隔X天执行一次任务-例如,我刚刚使用了Groovy的TimeCategory,并创建了一个不断运行的线程,并检查lastExecuted和当前时间之间的时间是否大于frequency enum指定的时间Schedule frequency enum

The problem - How do I deal with months? 问题 -我要如何处理几个月? If I set the frequency to monthly how do I handle the different length of months? 如果我将频率设置为每月一次,该如何处理不同的月份长度? One alternative, I guess, would be to have a large switch statement for every month. 我猜,一种替代方法是每个月都有一个很大的switch语句。 But that doesn't seem like a very good solution. 但这似乎不是一个很好的解决方案。 Is it possible to do this in a more elegant way ( preferably without any additional libraries or deprecated Java methods, like Date's getDay() method and etc. ) 是否可以以更优雅的方式做到这一点( 最好不要使用任何其他库或不推荐使用的Java方法,例如Date的getDay()方法等 )。

Thanks. 谢谢。

You can use the Calendar class, ie to schedule something on the 1st of each month: 您可以使用Calendar类,即在每个月的1号安排一些时间:

Calendar now = Calendar.getInstance();

now.set(Calendar.DAY_OF_MONTH, 1);


for (int i = 0; i < 10; i++)
{
     now.add(Calendar.MONTH, 1);
     scheduler.scheduleAt(now); // or whatever you are using to schedule
}

Although Date.getDay is deprecated, if you read the Javadoc on Date it points you to the replacement method for the deprecation. 尽管不推荐使用Date.getDay,但是如果您在Date上阅读了Javadoc,它将指向您替代不推荐使用的方法。

In this case, you may want to use the Calendar class to retrieve date and time information. 在这种情况下,您可能要使用Calendar类来检索日期和时间信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM