您好,登錄后才能下訂單哦!
本篇內容主要講解“怎么實現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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。