0

for a school project I have to calculate the 'hotItem' of a shoppingbag (which is the most popular item of that month). But I don't know how to call the method (getHotItem) every first day of the month. I've already did some research and found out about Timer and ScheduleExpressions, but from what I learned it is mostly used for a fixed time interval (which is not the case with months of 30 or 31days)

Is there a way to call this method at a specific date in the future(every 1st of the month)?

Thanks

TCode
  • 1
  • 1
    Make a java program that runs on boot, checks the date (`new Date()`, see http://stackoverflow.com/questions/9629636/get-todays-date-in-java ) and if the day equals 1 make your calculations. Happy coding :) -Charlie – Charlie Nov 17 '14 at 15:48
  • Probably needless tip: store the last date handled. Otherwise you risk on some break-down to either skip a month or do it twice. – Joop Eggen Nov 17 '14 at 15:55

1 Answers1

0

Avoid Timer Class In Servlets

If running in a web app environment, do not use the Timer class. Search StackOverflow to learn why.

ScheduleExpression

According to the Oracle Tutorial, a ScheduleExpression can be set for first of months. Looks like that class requires an EJB container. EJB is overkill for many people including me and my work, so I'm not familiar with that class.

ScheduledExecutorService

Another route without full EJB and Java EE is the Executor family of classes/interfaces. See the Tutorial. In particular look at the ScheduledExecutorService.

I would schedule it daily, have the task check for the current date. If not the first of the month, do nothing and that task completes. Tomorrow a new task will check for the date again, and so on.

Be sure to read the doc and search StackOverflow for that class to learn more. One trick is that your scheduled code can't throw any Exception or else the ScheduledExecutorService silently stops. So put a try-catch around your code.

For a web app environment ( Servlets only, or Java EE Web Profile, or full Java EE ) use a ServletContextListener to detect at runtime when the web app launching, and so start your ScheduledExecutorService. Likewise, you can shutdown. Again, search StackOverflow as this has been covered before.

Check Daily

You could try to calculate the amount of time until next first-of-month, but why bother? A quick check for today's date has virtually no impact on your server, and makes your code much simpler and avoid possible bugs due to your miscalculations. That is advice for the real world; perhaps the goal of your homework is to calculate date.

Another real-world tip: avoid the java.util.Date/.Calendar classes as they are notoriously troublesome, confusing, and flawed. Instead use either Joda-Time library or java.time package built into Java 8 (inspired by Joda-Time).

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154