需要的jar包
首先写自己的任务实体类
public class MyJob {
private String id;
private String name;
private String group;
private String status;
private String cron;
private String info;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCron() {
return cron;
}
public void setCron(String cron) {
this.cron = cron;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
接下来写自己要准备做的任务的类并实现接口Job下的方法
public class IntendJob implements Job {
private JobService jobService=new JobService();
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
jobService.intendmeet();
}
}
接下来写一个service(来在控制台提示计划的任务开始了)
public class JobService {
public void intendmeet()
{
System.out.println("您计划的任务开始了");
}
}
该写的类都完了,接下来new 一个spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="myJob" class="com.zhongxia.entity.MyJob">
<property name="id" value="1号"></property>
<property name="name" value="任务1"></property>
<property name="group" value="第1组"></property>
<property name="status" value="1"></property>
<!-- 在任意时刻的第30秒提示任务开始,可以百度cron表达式写法-->
<property name="cron" value="30 * * * * ? *"></property>
<property name="info" value="本次任务是....."></property>
</bean>
<!--任务信息-->
<bean id="jobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.zhongxia.job.IntendJob">
</property>
<property name="jobDataAsMap">
<map>
<entry key="Job">
<ref bean="myJob"></ref>
</entry>
</map>
</property>
</bean>
<!-- 配置触发器,触发器整合Job,调度器整合触发器 -->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="jobDetail"></property>
<property name="cronExpression" value="#{myJob.cron}" >
</property>
</bean>
<!--调度器-->
<bean id="schedulerFactory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger"></ref>
</list>
</property>
</bean>
</beans>
最后写一个测试类
public class Test {
public static void main(String[] args) throws SchedulerException {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
StdScheduler scheduler = (StdScheduler) context.getBean("schedulerFactory");
scheduler.start();
}
}
效果:(任意时刻第30秒提示任务开始,可以百度cron表达式来设置时间来提示任务开始)