How to Stop a Scheduled Task That Was Started Using @Scheduled Annotation

How to stop a scheduled task that was started using @Scheduled annotation?

Option 1: Using a post processor

Supply ScheduledAnnotationBeanPostProcessor and explicitly invoke postProcessBeforeDestruction(Object bean, String beanName), for the bean whose scheduling should be stopped.

Option 2: Maintaining a map of target beans to its Future

private final Map<Object, ScheduledFuture<?>> scheduledTasks =
new IdentityHashMap<>();

@Scheduled(fixedRate = 2000)
public void fixedRateJob() {
System.out.println("Something to be done every 2 secs");
}

@Bean
public TaskScheduler poolScheduler() {
return new CustomTaskScheduler();
}

class CustomTaskScheduler extends ThreadPoolTaskScheduler {

@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {
ScheduledFuture<?> future = super.scheduleAtFixedRate(task, period);

ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task;
scheduledTasks.put(runnable.getTarget(), future);

return future;
}

@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period) {
ScheduledFuture<?> future = super.scheduleAtFixedRate(task, startTime, period);

ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task;
scheduledTasks.put(runnable.getTarget(), future);

return future;
}
}

When the scheduling for a bean has to be stopped, you can lookup the map to get the corresponding Future to it and explicitly cancel it.

How to start/stop @Scheduled task after certain method finishes

A very simple way is to add a boolean switch:

@Scheduled(fixedRate = 1000)
public void scheduledTask() {
if (enabled) {
log.info("scheduled task has been started");
}
}

public void triggerStart() {
enabled = true;
log.info("after this @Scheduled task will start working");
}

public void triggerFinish() {
enabled = false;
log.info("after this @Scheduled task will stop working");
}

Start and stop scheduling task in Spring java

Try to use ScheduledExecutorService. For example, first of all create a ScheduledExecutorService:

ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());

then create a scheduled task:

ScheduledFuture<?> task = scheduledExecutorService.scheduleAtFixedRate(
() -> System.out.println("some task"), 0, 30, TimeUnit.SECONDS);

and when you want to cancel the task, do the following:

task.cancel(true);

How to conditionally enable or disable scheduled jobs in Spring?

@Component
public class ImagesPurgeJob implements Job {

private Logger logger = Logger.getLogger(this.getClass());

@Value("${jobs.mediafiles.imagesPurgeJob.enable}")
private boolean imagesPurgeJobEnable;

@Override
@Transactional(readOnly=true)
@Scheduled(cron = "${jobs.mediafiles.imagesPurgeJob.schedule}")
public void execute() {

//Do something
//can use DAO or other autowired beans here
if(imagesPurgeJobEnable){

Do your conditional job here...

}
}
}


Related Topics



Leave a reply



Submit