简体   繁体   中英

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

Both a stackoverflow and a Java beginner here.

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. 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.

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

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. 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. )

Thanks.

You can use the Calendar class, ie to schedule something on the 1st of each month:

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.

In this case, you may want to use the Calendar class to retrieve date and time information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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