Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheduling task using java spring mvc

I need to schedule a task to run automatically in java..I need the same functionality of window scheduling.I have done for daily,yearly but stuck when i came to weekly scheduling..not getting how to do this. I am using java calendar.Please help to find one good solutions.

Any help or ideas would be appreciable

like image 503
user3132347 Avatar asked Oct 17 '14 13:10

user3132347


1 Answers

Scheduling a task in Spring can be done in 4 ways, as shown below.

1. Task scheduling using fixed delay attribute in @Scheduled annotation.

public class DemoServiceBasicUsageFixedDelay {
    @Scheduled(fixedDelay = 5000)
    // @Scheduled(fixedRate = 5000)
    public void demoServiceMethod() {
        System.out.println("Method executed at every 5 seconds. Current time is :: " + new Date());
    }
}

2. Task scheduling using cron expression in @Scheduled annotation

@Scheduled(cron = "*/5 * * * * ?")
public void demoServiceMethod() {
    System.out.println("Method executed at every 5 seconds. Current time is :: " + new Date());
}

3. Task scheduling using cron expression from properties file.

@Scheduled(cron = "${cron.expression}")
public void demoServiceMethod() {
    System.out.println("Method executed at every 5 seconds. Current time is :: " + new Date());
}

4. Task scheduling using cron expression configured in context configuration

public class DemoServiceXmlConfig {
    public void demoServiceMethod() {
        System.out.println("Method executed at every 5 seconds. Current time is :: " + new Date());
    }
}

XML config for #4

<task:scheduled-tasks>
        <task:scheduled ref="demoServiceXmlConfig" method="demoServiceMethod" cron="#{applicationProps['cron.expression']}"></task:scheduled>
</task:scheduled-tasks>

More explanation on http://howtodoinjava.com/2013/04/23/4-ways-to-schedule-tasks-in-spring-3-scheduled-example/

Hope this helps you.

like image 67
Shishir Kumar Avatar answered Sep 25 '22 05:09

Shishir Kumar