简体   繁体   中英

Springboot: start a and stop programmatically a scheduled task

I have two different tasks, let's call them A and B.

Task A should start immediately (t0) and stop after a fixed time (t1), task B should start after a fixed time (t1) and run until i stop the service.

Both task A and B should do something every x seconds (for convenience, print a string). I know that in Springboot i can achive that using this annotation:

@Scheduled(fixedDelay = 6000)
private void taskA(){
   print("A")
}

But i have no clue how to start and stop each tasks after the time window has passed. I have made a simple scheme to help you understand better.

在此处输入图像描述

Thanks

You can schedule a task programatically via org.springframework.scheduling.TaskScheduler .

eg

    @Autowired
    private TaskScheduler taskScheduler;

    void scheduleTask(){
        final int xSeconds = 2000;
        PeriodicTrigger periodicTrigger = new PeriodicTrigger(xSeconds, TimeUnit.SECONDS);
        taskScheduler.schedule(
                () -> System.out.println("task B"),
                periodicTrigger
        );
    }

This acticle can also be helpful.

You can combine fixedRate with initialDelay annotation. So taskB runs after an initial delay of 6100 ms.

A --------- B ----- A -------- B ----- A ------>
t(0) t(5900) t(6000) t(1900) t(12000)

@Scheduled(fixedRate = 6000)
private void taskA(){
   System.out.println("A");
}

@Scheduled(fixedRate = 6000, initialDelay = 5000)
private void taskB(){
   System.out.println("B");
}

The @Scheduled annotation is for stuff that runs forever. Consider TaskScheduler for the task that must stop and @Scheduled for the task that should run until you stop the service.

Here is some code:

@Component
@RequiredArgsConstructor
public class Blam
implements
    Runnable
{
    private int count = 0;
    private ScheduledFuture<?> scheduledFuture = null;
    private final TaskScheduler taskScheduler;

    @Override
    public void run()
    {
        if (count < 6)
        {
            System.out.printf("%d: blam.taskA\n", count);
            ++count;
        }
        else
        {
            scheduledFuture.cancel(true);
        }
    }

    @PostConstruct
    public void postConstruct()
    {
        scheduledFuture = taskScheduler.scheduleWithFixedDelay(this, 1000);
    }
}

@Component
public class Kapow
{
    @Scheduled(initialDelay = 6000, fixedDelay = 1000)
    public void taskB()
    {
        System.out.println("Kapow.taskB");
    }
}

@RequiredArgsConstructor is a Lombok annotation, I highly recommend using Lombok. If you don't use Lombok, just inject the TashScheduler however you choose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM