spring中輕鬆實現定時任務,quartz表示式的線上Cron表示式生成器推薦
東西雖簡單,保留下來,開箱即用,省時省力!!!!!
1.首先在pom.xml中引入quartz相關包
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.3</version>
</dependency>
2.在spring 配置檔案中加入
<!--要排程的物件 -->
<bean id="jobBean" class="com.cqliving.cloud.controller.module.info.InfoClick" />
<bean id="jobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!-- 目標物件-->
<property name="targetObject" ref="jobBean" />
<!-- 執行目標物件的execute方法-->
<property name="targetMethod" value="execute" />
<property name="concurrent" value="false" />
</bean>
<bean id="trigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="jobDetail" />
<!--不熟悉表示式該怎麼寫的,請參照 表示式線上生成網站,很給力哦。--http://cron.qqe2.com/>
<property name="cronExpression" value="0 0 0/1 * * ? " />
</bean>
<bean id="startQuertz"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean"
lazy-init="false">
<property name="triggers">
<list>
<ref bean="trigger" />
</list>
</property>
</bean>
3.InfoClick類的程式碼為:
@Component
public class InfoClick {
public void execute() throws JobExecutionException {
System.out.println("開始執行定時任務-----");
}
}