How to create/ update task to run in future using Timer in microservice system

84 Views Asked by At

[Problem] I have service that have multiple instance and run in microservice system. In service, I use Timer instance to run task in future

public class CustomizedTimerTask extends TimerTask {

    private String message;
    private String sender;
    private String reciver;
    
    @Override
    public void run() {
        // todo somthing
    }

}

@Service
public MyTimerService {


    public void initAfterStartOn() {
        // get all task that have due date greater than now
        // for_each and call newTask() function
    }

    public void newTask() {
        
        Date startedAt = new Date(new Date().getTime() + ((long)5 * 60 * 60);
        
        CustomizedTimerTask timerTask = new CustomizedTimerTask();
        timerTask.setSender("sender");
        timerTask.setRevicer("receiver");
        timerTask.setMessage("Hi, nice to meet you");
        timer.schedule(new CustomizedTimerTask(), new Date(startedAt));
        
        // save CustomizedTimerTask to Database
    }
}

Everything will be ok if I run only one instance. But if I have multiple instance and one of all is down and run later. It will run initAfterStartOn() it cause task will be duplicate. Can someone give me advice on this?

Currently, I have not found any solution yet.

1

There are 1 best solutions below

0
Emirhan Naneli On

You can try using @Scheduled annotation

@Scheduled (cron = "0 0/10 * * * *", zone = "IST")
@SchedulerLock(name="createPromotionJob",lockAtLeastFor = "PTSM",lockAtMostFor="PTOM") 
public void scheduledCreatePromotion() {