Home > Software design >  Springboot: start a and stop programmatically a scheduled task
Springboot: start a and stop programmatically a scheduled task

Time:09-13

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.

enter image description here

Thanks

CodePudding user response:

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

e.g.

    @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.

CodePudding user response:

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");
}

CodePudding user response:

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.

  • Related