Programmatically configuring a scheduler in Spring makes it feasible to switch on/off of a scheduling tasks in shell.
This entry shows a scenario where I need to start heartbeat generator and stop it; the benefit of doing this is that I could dynamically control event generation, publication and subscription.
The application.properties has a parameter for “infra.ebs.heartbeat.cron” for 1 second interval; if not found, it uses 1 minute interval by default.
Shell command “heartbeat –start” will start scheduler to make HeartBeatGenerator to generate and publish HeartBeatEvent.
Shell command “heartbeat” by default will disable the publishing.
package com.hedge.panda.shell.play;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import com.hedge.panda.infra.ebs.HeartBeatGenerator;
/**
* @author wofon
*
*/
@ShellComponent
public class EventCommands {
@Value("${infra.ebs.heartbeat.cron:* */1 * * * *}")
private String cron;
public EventCommands() {
}
@Autowired TaskScheduler scheduler;
private ScheduledFuture<?> task = null;
@Autowired HeartBeatGenerator generator;
@ShellMethod("heart beat start to generate events at 1 sec interval.")
public String heartbeat(boolean start) {
if(start) {
task = this.scheduler.schedule(
new TimerTask() {
@Override
public void run() {
generator.generateEvent();
}
},
new CronTrigger(cron)
);
return "heartbeat starts ticking...";
}else {
if(task!=null) {
task.cancel(true);
}
return "heartbeat canceled.";
}
}
}
2 thoughts on “Start And Stop Heartbeat In Shell”