Reputation:
I am doing a spring boot project. Here is main method and a controller method
@SpringBootApplication
@ComponentScan(basePackages="nokia.quartz")
@EnableScheduling
public class App
{
public static void main( String[] args )
{
ConfigurableApplicationContext context =SpringApplication.run(App.class, args);
}
}
Controller:
@RestController
public class Controller {
@Autowired
private SampleTask m_sampletask;
@RequestMapping(value = "start", method = RequestMethod.GET)
public void start() throws Exception {
m_sampletask.work();
}
}
And a Sample class
@Component
public class SampleTask {
String cron_expression="0 0/1 * * * ?";
public void work() {
System.out.println("");
}
}
What the problem here is the rest call "/start" should make the SampleTask work() method a schedule job with the given cron expression when I am calling it from from rest endpoint "/start". Also I should be able to configure it at runtime with another rest endpoint as well as stop it..
Upvotes: 1
Views: 11629
Reputation: 703
@EnableScheduling
annotation and @Scheduled(cron= 0 0/1 * * * ?)
for creating a scheduler in Spring boot.
Please add @EnableScheduling
at starting of App Class and @Scheduled
to the method which you want to run using cron.PFB the useful link.
https://spring.io/guides/gs/scheduling-tasks/
@Autowired TaskScheduler taskScheduler; ScheduledFuture<?> scheduledFuture; @RequestMapping(value = "start", method = RequestMethod.GET) public void start() throws Exception { scheduledFuture = taskScheduler.scheduleAtFixedRate(m_sampletask.work(), FIXED_RATE); }
@Component
public class SampleTask implements Runnable {
String cron_expression="0 0/1 * * * ?";
@Override public void run() { System.out.println("Hello"); }
}
Upvotes: 1