定时任务 流程

定时任务列表

		<br> <br>
		<button class="btn btn-primary pull-left" type="button" id="retu">返回</button>
		<br> <br> <br>
		<form class="yzForm" id="editFrom">
			<div id="toolbar" class="form-group" style="height: 50px; display:none;">
				<strong>id:</strong><input class="form-control" type="text" 
					id=quartzId name="quartzId" style="margin: 5px;"></input>
			</div>
			<div id="toolbar" class="form-group" style="height: 50px;">
				<strong>任务名:</strong><input class="form-control" type="text"
					id=name name="name" style="margin: 5px;"></input>
			</div>
			<div id="toolbar" class="form-group" style="height: 50px;">
				<strong>任务组:</strong><input class="form-control" type="text"
					id="group" name="group" style="margin: 5px;"></input>
			</div>
			<div id="toolbar" class="form-group" style="height: 50px;">
				<strong>定时规则:<span id="sidebar"><a href="http://cron.qqe2.com/" target='_BLANK'>获取Cron 表达式</a></span></strong><input class="form-control" type="text"
					id="cron" name="cron" style="margin: 5px;"></input>
			</div>
			<div id="toolbar" class="form-group" style="height: 50px;">
				<strong>任务类:</strong><input class="form-control" type="text"
					id="className" name="className" style="margin: 5px;"></input>
			</div>
		
		</form>
			<button id="save" type="button" class="btn btn-primary" >提交</button>
	</div>

var save = document.getElementById("save");
//提交
save.onclick = function() {
	
	var form = $('#editFrom').serialize();
	var id=	document.getElementById('quartzId').value;
	debugger
	//提交新建的form表单task
	if(id==""){
			 	$.ajax({
			 		url : "/manage/addtask",
					data :form,
					type : "post",
					datType : "json",
					success : function(result) {
						debugger
						if (result) {	alert("成功");$('.adddate').hide(); $('.canceldate').show();
						$("#tabled").bootstrapTable('refresh');
						} else {alert("失败");}
					}
				});
			 	} else {	//提交修改的form表单task
					$.ajax({
				 		url : "/manage/updatetask", // 目标地址
						data :form,
						type : "post",
						datType : "json",
						success : function(result) {
							if (result) {alert("成功");$('.adddate').hide(); $('.canceldate').show();
							$("#tabled").bootstrapTable('refresh');
							}else{
								alert("失败");
							}
						}
					});
				}
		}

// 加入Qulifier注解,通过名称注入bean
@Autowired

@Qualifier(“Scheduler”)
public Scheduler scheduler;
@Autowired
ScheduleJobService ScheduleJobServiceImpl;
//新建
@RequestMapping("/addtask")
@ResponseBody
public Map<String,Object> addJob( Task task) throws Exception {
Map<String,Object> resMap= new HashMap<String,Object>();
ScheduleJobServiceImpl.addJob(task);
resMap.put(“result”, true);
return resMap;
}

package com.sr.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sr.entity.Task;
import com.sr.mapper.db1.TimingTaskDao;
import com.sr.service.BaseJob;
import com.sr.service.ScheduleJobService;

@Service
@Transactional
public class ScheduleJobServiceImpl implements ScheduleJobService{
// private static final int Task = 0;
@Autowired
@Qualifier(“Scheduler”)
private Scheduler scheduler;
@Autowired TimingTaskDao timingtaskdao;
// 自己选择所用的dao
/*
* @Autowired TaskService taskService;
*/

//新增一个任务
public String addJob(Task task) throws Exception {

	// 启动调度器
	scheduler.start();

	// 构建job信息 任务名,任务组,任务执行类
	JobDetail jobDetail = JobBuilder.newJob(getClass(task.getClassName()).getClass())
			.withIdentity(task.getName(), task.getGroup()).build();

	// 表达式调度构建器(即任务执行的时间)
	CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(task.getCron());

	// 按新的cronExpression表达式构建一个新的trigger
	CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(task.getName(), task.getGroup())
			.withSchedule(scheduleBuilder).build();

	try {
		Date date  = scheduler.scheduleJob(jobDetail, trigger);
		if(date!=null){
			timingtaskdao.addtask(task);
		}
		
		
	} catch (SchedulerException e) {
		e.printStackTrace();
	}
	return "success";
}

//批量暂停

@Override
public JobDetail jobPause(List<Task> task) throws Exception {
	
	for (int i = 0; i < task.size(); i++) {
	scheduler.pauseJob(JobKey.jobKey(task.get(i).getName(),task.get(i).getGroup()));
	timingtaskdao.pausetask(task.get(i).getName(),task.get(i).getGroup());
	}
	return null;
}
//恢复一个任务
@Override
public JobDetail startJob(String jobName, String jobGroupName) throws Exception {
	  JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
    scheduler.resumeJob(jobKey);
	timingtaskdao.statetask(jobName, jobGroupName);
	JobDetail detail = scheduler.getJobDetail(JobKey.jobKey(jobName, jobGroupName));
	
	return detail;
}
//批量删除
@Override
public void jobDetele(List<Task> task) throws SchedulerException {
	List<Integer> q1 = new ArrayList<>();
	List<JobKey> q2 = new ArrayList<>();
	for (int i = 0; i < task.size(); i++) {
		JobKey jobKey = JobKey.jobKey(task.get(i).getName(), task.get(i).getGroup());
   	q1.add(task.get(i).getQuartzId());
   	q2.add(jobKey);
	}
	scheduler.deleteJobs(q2);
   timingtaskdao.deletetask(q1);
}

public void jobreschedule(Task task) throws Exception {
	String  jobName=task.getName();
	String	jobGroupName=task.getGroup();
	String	cronExpression=task.getCron();
	try {
		TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroupName);
		// 表达式调度构建器
		CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);

		CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

		// 按新的cronExpression表达式重新构建trigger
		trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

		// 按新的trigger重新设置job执行
		Date date =scheduler.rescheduleJob(triggerKey, trigger);
		if(date!=null){
			timingtaskdao.updatetask(task);
		}
		
	} catch (SchedulerException e) {
		System.out.println("更新定时任务失败" + e);
	}
}
private static BaseJob getClass(String classname) throws Exception {
	Class<?> class1 = Class.forName(classname);
	return (BaseJob) class1.newInstance();
}


//新建
public int addtask(Task task) {
	int result=0;
	int min=1;
	int max=10000000;
	int intBounded = min + ((int) (new Random().nextFloat() * (max - min)));
	int quartzId = intBounded;
	task.setQuartzId(quartzId);	
	result=timingtaskdao.addtask(task);
   return result;
}

//根据id修改task字段

public int updatetask(Task task, Integer quartzId) {
	int result=0;
	task.setQuartzId(quartzId);	
	result=timingtaskdao.updatetask(task); 
	return result;
}

}

<?xml version="1.0" encoding="UTF-8"?> SELECT * FROM task SELECT * FROM task quartzId=#{_parameter} insert into Task ( name, className, `group`, cron, state ) values (
	<if test="name!=null  and name !='' ">
	#{name,jdbcType = VARCHAR },
	</if>
	<if test="className!=null  and className !='' ">
	#{className,jdbcType = VARCHAR },
	</if>
	<if test="group!=null and group !=''">
	#{group,jdbcType = VARCHAR },
	</if>
	<if test="cron!=null and cron !=''">
	#{cron,jdbcType = VARCHAR },
	</if>
	"ACQUIRED"
)
update task name=#{name,jdbcType = VARCHAR },
	<!-- className -->
	<if test="className !=null  and className !='' ">
		className=#{className,jdbcType = VARCHAR },
	</if>
	
	<!-- group -->
	<if test="group !=null  and group !='' ">
		`group`=#{group,jdbcType = VARCHAR },
	</if>
	
	<!-- cron -->
	<if test="cron !=null  and cron !='' ">
		cron=#{cron,jdbcType = VARCHAR },
	</if>		
		<!-- cron -->
	<if test="state !=null  and state !='' ">
		state=#{state,jdbcType = VARCHAR }
	</if>	
</set>
<where>
		quartzId=#{quartzId}
</where>
update task state="PAUSED" `group`=#{group} and name=#{name}
	update task
<set>
		state="ACQUIRED"
</set>
<where>
	 	`group`=#{group} and
		 name=#{name} 
</where>
delete from task where quartzId in(

item=“quartzId” separator =",">
(
#{quartzId}
)
)

delete from task quartzId=#{quartzId}

package com.sr.config;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

import com.sr.entity.Task;
import com.sr.service.ScheduleJobService;
import com.sr.service.impl.TimingTaskService;

@Configuration
public class JobListener implements ApplicationListener {

@Autowired
ScheduleJobService ScheduleJobServiceImpl;
@Autowired
private TimingTaskService TimingTaskServiceImpl;
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
     List<Task> tasks = TimingTaskServiceImpl.selectTask();
    //List<Task> tasks = new ArrayList<Task>();
    
    //tasks.add(new Task(1,"fen", "com.sr.service.impl.TestJob", "fen1", "0 */1 * * * ?"));
    System.out.println("task size = " + tasks.size());
    try {
        for (Task task : tasks) {
        	//ScheduleJobServiceImpl.addJob(task);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

package com.sr.config;

import java.io.IOException;
import java.util.Properties;

import org.quartz.Scheduler;
import org.quartz.ee.servlet.QuartzInitializerListener;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
public class QuartzConfig {

@Bean(name="SchedulerFactory")
public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
	
	
	  PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
	  propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
	    //在quartz.properties中的属性被读取并注入后再初始化对象
	  propertiesFactoryBean.afterPropertiesSet();
	    //创建SchedulerFactoryBean
	    
	   
	    
    SchedulerFactoryBean factory = new SchedulerFactoryBean();
    //factory.setQuartzProperties(quartzProperties());
    
    factory.setQuartzProperties(propertiesFactoryBean.getObject());
    return factory;
}

/*
 * quartz初始化监听器
 */
@Bean
public QuartzInitializerListener executorListener() {
    return new QuartzInitializerListener();
}

/*
 * 通过SchedulerFactoryBean获取Scheduler的实例
 */
@Bean(name="Scheduler")
public Scheduler scheduler() throws IOException {
    return schedulerFactoryBean().getScheduler();
}

/**
 * 设置quartz属性,可以从properties配置中读取
 */
public Properties quartzProperties() throws IOException {
    Properties prop = new Properties();
    prop.put("quartz.scheduler.instanceName", "ServerScheduler");
    prop.put("org.quartz.scheduler.instanceId", "AUTO");
    prop.put("org.quartz.scheduler.skipUpdateCheck", "true");
    prop.put("org.quartz.scheduler.instanceId", "NON_CLUSTERED");
    prop.put("org.quartz.scheduler.jobFactory.class", "org.quartz.simpl.SimpleJobFactory");
    prop.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
    prop.put("org.quartz.threadPool.threadCount", "5");
    prop.put("org.quartz.threadPool.threadPriority", "5");
    //存入数据库表中
    prop.put("org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread", "true");
    prop.put("org.quartz.jobStore.misfireThreshold", "5000");
    prop.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
    prop.put("org.quartz.jobStore.tablePrefix", "QRTZ_");
    prop.put("org.quartz.jobStore.dataSource", "sr");
    prop.put("org.quartz.dataSource.sr.driver", "com.mysql.jdbc.Driver");
    prop.put("org.quartz.dataSource.sr.URL", "jdbc:mysql://192.168.10.233:3306/edb?useUnicode=true&characterEncoding=UTF-8");
    prop.put("org.quartz.dataSource.sr.user", "root");
    prop.put("org.quartz.dataSource.sr.password", "tom");
    prop.put("org.quartz.dataSource.sr.maxConnection", "10");
  //设置数据源

    return prop;
}

}

quartz.scheduler.instanceName=ServerScheduler
org.quartz.scheduler.instanceId=AUTO
org.quartz.scheduler.skipUpdateCheck=true
org.quartz.scheduler.instanceId=NON_CLUSTERED
org.quartz.scheduler.jobFactory.class=org.quartz.simpl.SimpleJobFactory
org.quartz.threadPool.class=org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount=5
org.quartz.threadPool.threadPriority=5

org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread=true
org.quartz.jobStore.misfireThreshold=5000
org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.tablePrefix=QRTZ_
org.quartz.jobStore.dataSource=sr
org.quartz.dataSource.sr.driver=com.mysql.jdbc.Driver
org.quartz.dataSource.sr.URL=jdbc:mysql://192.168.10.233:3306/edb?useUnicode=true&characterEncoding=UTF-8
org.quartz.dataSource.sr.user=root
org.quartz.dataSource.sr.password=tom
org.quartz.dataSource.sr.maxConnection=10

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值