一、使用的技術:
- Gradle
- Java annotation
- Spring Boot
dependencies { compile 'org.springframework.boot:spring-boot-starter:1.2.7.RELEASE' compile 'org.quartz-scheduler:quartz:2.2.2' compile 'org.springframework:spring-context-support:4.1.8.RELEASE' }三、開始寫程式
首先建置Service,定義將在排程中執行的類別和方法,
在此範例中我定義了一個打招呼以及定期print時間的功能。
package app.service; import java.util.Calendar; public class HelloService { public void Hello(){ System.out.println("Hello!Jason"); System.out.println(Calendar.getInstance().getTime()); } }
接著建置一個SchedulConfig,
使用Java annotation 的方式來產生(管理)Spring製造的bean。
package app.config; import org.quartz.Trigger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.quartz.CronTriggerFactoryBean; import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean; import org.springframework.scheduling.quartz.SchedulerFactoryBean; @Configuration public class SchedulConfig { @Bean //1.將HelloService納入Spring來管理 public HelloService helloService(){ return new HelloService(); } @Bean @Autowired //2.建立helloJob,將HelloService注入,指定執行的方法名稱 public MethodInvokingJobDetailFactoryBean helloJob(HelloService helloService){ MethodInvokingJobDetailFactoryBean bean = new MethodInvokingJobDetailFactoryBean(); bean.setTargetObject(helloService); bean.setTargetMethod("Hello"); return bean; } @Bean @Autowired //3.建立helloTrigger,將helloJob注入,指定執行的時間,參數依序是 秒 分 時 ...etc public CronTriggerFactoryBean helloTrigger(MethodInvokingJobDetailFactoryBean helloJob){ CronTriggerFactoryBean bean = new CronTriggerFactoryBean(); bean.setJobDetail(helloJob.getObject()); bean.setCronExpression("0/10 * * * * ? "); return bean; } @Bean @Autowired //4.建立scheduler,可執行多個Trigger public SchedulerFactoryBean schedulerFactoryBean(CronTriggerFactoryBean helloTrigger){ SchedulerFactoryBean bean = new SchedulerFactoryBean(); Trigger[] triggers = {helloTrigger.getObject()}; bean.setTriggers(triggers); return bean; } }
接著Spring boot執行程式的方式如下:
package app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub SpringApplication.run(Application.class, args); } }
使用eclipse直接run application或是export jar執行都可以喔XDDDD
程式結果:
Hello!Jason Sat Nov 07 22:25:30 CST 2015 Hello!Jason Sat Nov 07 22:25:40 CST 2015 Hello!Jason Sat Nov 07 22:25:50 CST 2015 Hello!Jason Sat Nov 07 22:26:00 CST 2015 ...