您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
本篇内容主要讲解“怎么实现MainStarter”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么实现MainStarter”吧!
从触发器中配置一个通用触发MainStarter
<bean id="mainStarter" class="com.zb.timer.MainStarter" > </bean> <bean id="mainStarterDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="mainStarter" /> <property name="targetMethod" value="run" /> <property name="concurrent" value="false" /> </bean> <bean id="mainStarterTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean"> <property name="jobDetail" ref="mainStarterDetail" /> <property name="startDelay" value="10000" /> <property name="repeatCount" value="0" /> </bean> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="mainStarterTrigger" /> </list> </property> </bean>
public class MainStarter{ // 任务中心 private TaskCenter taskCenter; public void setTaskCenter(TaskCenter taskCenter) { this.taskCenter = taskCenter; } public void run() { if(taskCenter==null) { taskCenter = new TaskCenterSupport(); } taskCenter.run(); } }
public interface TaskCenter { // 加载任务 public void loadTask(Task taskTracker); public List<Task> getTasks(); public void run(); public void terminate(); }
任务中心存储任务,任务 Task 为代码最终执行
public abstract class Task extends Thread { private boolean isAlive = true; @Override public void run() { while (isAlive) { try { doRun(); } catch (Exception e) { logger.error("run task error.", e); } } } public void setAlive(boolean isAlive) { this.isAlive = isAlive; } // 子类业务需要实现此方法,方法中为具体业务 protected abstract void doRun() throws Exception; }
public class TaskCenterSupport implements TaskCenter { private List<Task> tasks; public List<Task> getTasks() { return tasks; } public void loadTask(Task task) { if (tasks == null) { tasks = new ArrayList<>(); } tasks.add(task); } public void run() { if(CollectionUtils.isNotEmpty(tasks)){ for (Task task : tasks) { if(task != null) { task.setAlive(true); task.start(); } } } } public void terminate() { if(CollectionUtils.isNotEmpty(tasks)){ for (Task task : tasks) { if(task != null) { task.setAlive(false); } } tasks.clear(); try { Thread.sleep(5000); } catch (InterruptedException e) { logger.error(e.getMessage(),e); Thread.currentThread().interrupt(); } } } }
public class ZBTask extends Task{ public ZBTask () { TaskCenter taskCenter = TaskCenterSingleton.getInstance(); taskCenter.loadTask(this); } public void doRun() throws Exception { /* 具体业务实现,这里就能会定时执行, * 若有需要还可以在此使用休眠, * 这样只会把此线程挂起,不影响其他 Task 子类的执行 */ } }
到此,相信大家对“怎么实现MainStarter”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。