summaryrefslogtreecommitdiffstats
path: root/src/main/java/net/libertacasa/pubsh/web/SchedulerBean.java
blob: e0bfd247c791ed5f5905981cbb0ebbbf9746dba4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package net.libertacasa.pubsh.web;

import java.time.Duration;
import java.time.Instant;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.github.kagkarlsson.scheduler.Scheduler;
import com.github.kagkarlsson.scheduler.task.Task;
import com.github.kagkarlsson.scheduler.task.helper.Tasks;
import static com.github.kagkarlsson.scheduler.task.schedule.Schedules.fixedDelay;

@Configuration
public class SchedulerBean {

    @Bean
    Task<Void> recurringSampleTask(CounterService counter) {
        return Tasks
            .recurring("recurring-sample-task", fixedDelay(Duration.ofMinutes(1)))
            .execute((instance, ctx) -> {
                System.out.printf("Recurring testing task. Instance: %s, ctx: %s\n", instance, ctx);
                CounterService.increase();
            });
    }

    @Bean
    Task<Void> sampleOneTimeTask() {
        return Tasks.oneTime("one-time-sample-task")
            .execute((instance, ctx) -> {
                System.out.printf("OK, one-shot testing task.\n");
            });
    }
    
    @Bean
    CommandLineRunner executeOnStartup(Scheduler scheduler, Task<Void> sampleOneTimeTask) {
        System.out.println("Scheduling one-shot testing task to execute now.");

        return ignored -> scheduler.schedule(
            sampleOneTimeTask.instance("command-line-runner"),
            Instant.now()
        );    
   }
}