2

I am developing Java REST Web Service using Spring and Hibernate. I need to implement a feature to schedule a future task. For example, When User Sign Up in my application I have to credit him 100 virtual credits to his account for first six months. Like this there is some more similar features.

I am thinking like TimerTask can be used for this feature. The problem is If I create Timer for each users who sign up, I can't able to stop Timer of specific user if he goes inactive and it seems like dumping Thread in memory. If 1000 users sign up there will be 1000 TimerTask Threads.

How to implement this kind of feature using Spring or Java? I should have the full control over the Thread, I can able to stop thread If I want.

Mdumanoj
  • 517
  • 3
  • 9
  • 27
  • and you are sure your program is running this long without a need to restart or a failure forcing restart? I think you rather need a solution to store this data somewhere and regularly checking the timed conditions – P.J.Meisch Apr 15 '17 at 06:25
  • Yes. I am using Tomcat Server. It will crash sometime and go down, then I need to restart server to get it back. – Mdumanoj Apr 15 '17 at 16:48
  • see https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html – rvit34 Apr 16 '17 at 08:03

1 Answers1

0

you can use a Single thread to perform a task with @scheduled annotation and minimal XML configuration, I'll leave the link for your reference.

you're just required to create a method in your service and place @Scheduled annotation like

@Scheduled(cron = "0 15 10 15 * ?")
public void scheduleTaskUsingCronExpression(){
long now = System.currentTimeMillis() / 1000;
System.out.println("schedule tasks using cron jobs - " + now);
}
  • Yes by using this I can schedule a Job. But how can I stop the Job. If I scheduled Job to execute for each 10 mins and for some reasons I want to stop this execution, How can I do that? – Mdumanoj Apr 17 '17 at 07:12
  • Don't try to stop the job! Instead have a Boolean check inside scheduled task! And you can change the Boolean variable to stop and start the service... Kindly upvote and accept my answer if it works! – Sadham Hussain Apr 17 '17 at 07:15
  • I don't think this is the right way to do. Because actually `TimerTask` is running and it will run forever. – Mdumanoj Apr 18 '17 at 10:25