javasingletonscheduled-tasksejbjava-ee-8

Schedule method is executed twice


i have a method which needs to be executed at a specific time. I use @Schedule annotation to achieve this. When the method is executed it sends an email. The schedule works and the mail is sent at the time i want but it is sent twice so the method is somehow executed twice. Here is my code:

@Singleton
public class ScheduledClass{

    @EJB
    private SomeService someService;

    @Schedule(hour = "17", minute = "10", persistent = false)
    public void scheduledMethod(){
        try{
            //here i send the mail
        }
    }
}

I'm not sure if this executed twice thing is happening because of the Singleton annotation. Can someone help?


Solution

  • I actually solved this using the logic of @ShedLock annotation of Spring. Created a column in a table called schedule_lock and set it 0 as default. when one of the two instances start working at the scheduled time it will set the schedule_lock value to 1. (there is an if control to check schedule_lock, if it's 1 the scheduled job wont be executed.) when the instance that was actively executing the job finishes, it sets the schedule_lock to 0