Spring Scheduler: toggle between using cron and running once on startup

1.4k views Asked by At

I managed to get a simple app running with spring application context and managed to get it working on a schedule via @Scheduled:

@Scheduled(cron= "0 30 9 * * *, zone="Australia/Sydney")

Is there a way to get @Scheduled to run on startup?

What I had in mind is to have a toggle in application.properties e.g:

scheduler.triggernow=true

Where if it is set to true, the app ignores the spring cron schedule and runs now (runs once on startup), and if set to false then it will use the spring cron schedule above and runs every day at 9:30am

  1. I went to https://start.spring.io to get a basic application to work with (maven project, java, spring boot 2.3.4)

  2. I saw a YouTube video to help set up a scheduler:

In the main class i have

@SpringBootApplication

@EnableConfigurationProperties

public class Demo{

public static void main(String[] args){ 

  ConfigurationApplicationContext ctx = new SpringApplicationBuilder(Demo.class)

  .web(WebApplicationType.None)

  .run(args)

}

}

In a new class I added:

@Configuration

@EnableScheduling @ConditionalOnProperty(name="scheduling.enabled", matchIfMissing=true)

public class Jobsched{


    @Scheduled(cron="0 30 9 * * *",zone="Australia/Sydney") 

        public void test(){ 

         System.out.println("hello"); 

        }

}

On its own the cron scheduler works. And I have a property that can disable it. I would only want to disable it if I want to run it once on startup (currently disabling it will mean it does nothing)

This is a nonprod application by the way. Plan is to deploy this with scheduler running. And if I want to run it locally then just disable the scheduler and have it run on startup

1

There are 1 answers

1
Bourbia Brahim On

Use the @PostConstruct in your class component (or service ...) to execute the code in startup,

below example showing how to proceed :

@Component
public class MyClass {
 
    
    @PostConstruct
    private void methodToExecute() {
        doScheduledWOrk(); // call here for startup execution
    }

    @Scheduled(cron= "0 30 9 * * *, zone="Australia/Sydney")
    public void scheduleMethod() {
         doScheduledWOrk(); // sample function
    }

    public void doScheduledWOrk() {
         //doing some scheduled stuff here... 
    }
}