user5761419
user5761419

Reputation:

Start a new Schedule Job by rest call in Spring Boot

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

Answers (1)

Sahil
Sahil

Reputation: 703

  1. You can make use combination of @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/

  1. You can try below option
    @Autowired     
    TaskScheduler taskScheduler;
    ScheduledFuture<?> scheduledFuture;
    @RequestMapping(value = "start", method = RequestMethod.GET)
    public void start() throws Exception { 
      scheduledFuture = taskScheduler.scheduleAtFixedRate(m_sampletask.work(), FIXED_RATE);
     }
    

Runnable Code of Nawaz:

@Component 
public class SampleTask implements Runnable { 
    String cron_expression="0 0/1 * * * ?"; 
    @Override public void run() { System.out.println("Hello"); } 
}

Upvotes: 1

Related Questions