Search code examples
grailsgroovyscheduled-tasks

Execute Task Everyday at Midnight - Grails 3.2.2


I have a method like MyController.foo() and I want to execute it every day at 00:00.

I have seen some solutions that use a TimerTask with a 1 day delay in seconds, but the day of time change it will bring some errors.

So ... What is the most efficient way to achieve this?


Solution

  • First you need to enable scheduling using spring boot annotation:

    @EnableScheduling
    class Application extends GrailsAutoConfiguration {
        static void main(String[] args) {
            GrailsApp.run(Application, args)
        }
    }
    

    Then you can put @Scheduled annotation on your methods:

    @Scheduled(cron="00 00 * * *")
    def foo() {
        //do something
    }
    

    Cron expression 00 00 * * * means execute every midnigth.