Examples of Java multithreading--quartz timing scheduling

Source: Internet
Author: User

Java Multithreaded directory:

Java Multithreading-Basic knowledge

Java Multithreading--synchronized Keywords

Java Multithreading--an example of a timed dispatch

Examples of Java multithreading--quartz timing scheduling

Java Multithreading--thread wait and wake

Overview

Part 1th Distribution

Part 2nd code example

Part 1th Distribution

API documentation for Quartz address: Quartz Enterprise Job Scheduler 1.8.6 API

Main interface Directory:

Focus on the next few job,scheduler,trigger,jobdetail:

The class that represents the task inherits the job interface, which has only one method execute, and the corresponding scheduler scheduler invokes the task when a trigger for a task is started.

Quartz does not save an actual job class, but instead by allowing you to define a jobdetail.

Scheduler represents the registration form for jobdetails and triggers, and scheduler is produced by Schedulerfactory.

 

The configuration file for Quartz quartzconfig.xml is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Security= "http://www.springframework.org/schema/security" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" Xmlns:tx = "Http://www.springframework.org/schema/tx" xmlns:context= "Http://www.springframework.org/schema/context" xmlns: Jee= "Http://www.springframework.org/schema/jee" xmlns:mvc= "Http://www.springframework.org/schema/mvc" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring- Beans-3.1.xsd Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/ Spring-mvc-3.1.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security /spring-security-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http:Www.springframework.org/schema/aop/spring-aop-3.1.xsd Http://www.springframework.org/schema/tx Http://www.spri Ngframework.org/schema/tx/spring-tx-3.1.xsd Http://www.springframework.org/schema/cache Http://www.springframewo Rk.org/schema/cache/spring-cache-3.1.xsd Http://www.springframework.org/schema/jdbc HTTP://WWW.SPRINGFRAMEWORK.O Rg/schema/jdbc/spring-jdbc-3.1.xsd Http://www.springframework.org/schema/jee Http://www.springframework.org/sche Ma/jee/spring-jee-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/JMS Http://www.springframework.org/schema/jms/sp Ring-jms-3.1.xsd Http://www.springframework.org/schema/lang Http://www.springframework.org/schema/lang/spring-la Ng-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/OXM Http://www.springframework.org/schema/oxm/spring-oxm-3.1.xs          D Http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd Http://www.springframework.Org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd http://www.springframework.org/ Schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd "> <!--================ ======================================================================-<!--Interceptor configuration file--<!--======= ===============================================================================--><!--<bean id= " Startquartz "lazy-init=" false "autowire=" no "class=" Org.springframework.scheduling.quartz.SchedulerFactoryBean " > </bean> <!--================================================================================        ======-<!--work class to invoke-<bean id= "Quartzjob" class= "Com.util.CallQuartz" ></bean> <!--define methods for calling objects and calling objects--<bean id= "Jobtask" class= "Org.springframework.scheduling.quartz.MethodInvoki    Ngjobdetailfactorybean "> <!--called Class--        <property name= "TargetObject" > <ref bean= "quartzjob"/> </property> <!--calling methods in classes--<property name= "Targetmethod" > &LT;VALUE&GT;CALLALLQUARTZ&L T;/value> </property> </bean> <!--define trigger time-<bean id= "Dotime" cl                ass= "Org.springframework.scheduling.quartz.CronTriggerBean" > <property name= "Jobdetail" > <ref bean= "Jobtask"/> </property> <!--cron expression---<property name= "Cronexpression" > &LT;VALUE&GT;*/10 * * * * *?</value> </property> </bea N> <!--general Management class if lazy-init= ' false ' then the container starts executing the scheduler--<bean id= "Startquertz" lazy-init= "false" au Towire= "No" class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean" > <property name= "triggers" > <list> <ref bean= "Dotime"/> </list> </property> &L T;/bean> <!--======================================================================================--   </beans>

Add the appropriate load profile path to the Web. xml file.

Part 2nd code example

First define the class of a task

  1 package com.util.vo;  2 3 Import java.io.IOException;  4 Import java.net.HttpURLConnection;  5 Import java.net.MalformedURLException;  6 Import Java.net.URL;  7 Import Java.util.ArrayList;  8 Import Java.util.HashMap; 9 Import java.util.List; Ten import Java.util.Map; Import Org.apache.log4j.Logger; Import Org.quartz.Job; Import Org.quartz.JobExecutionContext; Org.quartz.JobExecutionException import; */** * @ClassName: Quartzvo * * @author xingle * @date 2014-8-14 pm 12:49:25/PU  Blic class Quartzvo implements job{public static int Id = 0; private static Logger Logger = Logger.getlogger (Quartzvo.class); 30//Cache task list in public static list<quartzvo> quartzlist = new arraylist<quartzvo> (); 32//Cache task Map in public static map<string, quartzvo> Quartzmap = new hashmap<string, quartzvo> (); /** PNS * ID * * *ing ID; 40/** 41 * Task Name * */public String jobtitle; 44/** 45 * Dispatch Path * */public String Jcallpath; 48/** 49 * Trigger expression: */n-public String Jobcron; /** * @Fields s_date: Start time * */public String s_date; /** * @Fields cycle: Cycle Indication: 1 cycles, 2 single-time, +/-public String cycle; The public string getId () {The return ID; the setId of the public void (string id) {Thi S.id = ID; Getjobtitle () () () () () () {jobtitle; n}-public void Setjobtitle (String j Obtitle) {this.jobtitle = jobtitle; * * * The public String Getjcallpath () {return Jcallpath ;  Setjcallpath} public void (String jcallpath) {this.jcallpath = Jcallpath;     String Getjobcron () {Jobcron, Bayi}, Setjobcron public void (string Jobcron) {83    This.jobcron = Jobcron; \ n}-Public String getcycle () {return cycle; setcycle}-public void (string cycle) {8 9 this.cycle = cycle;  A. Gets_date public String () {s_date return; 94} The public void Sets_date (string S_date) {this.s_date = s_date; 97} 98/** 99 * Perform task * @Description: 101 * @param a     rg0102 * @throws JobExecutionException103 * @author xingle104 * @data 2014-8-14 pm 12:51:35105 */106 @Override107 public void Execute (jobexecutioncontext context) throws Jobexecutionexception {108 String Jobna me = Context.getjobdetail (). GetName (); 109 Logger.debug ("timed task" + JobName + "will execute start!!         "); Quartzvo Quartzvo = QuartzVo.quartzMap.get (jobName); 111 String inurl = Quartzvo.getjcallpath (); 112 URL url = null;113 httpurlconnection conn = null;114 try {url = new URL (INURL); conn = (httpurlconnection) url.openconnection (); 117} catch (Malformedurlexception e) {118  E.printstacktrace (); 119} catch (IOException e) {System.out.println ("***************** Connection failed, program address: "+ inurl"); 121 e.printstacktrace (); 122}123 try {124 if (conn.getresp Onsecode ()! = HTTPURLCONNECTION.HTTP_OK) {System.out.println ("****************** Dispatch failed!!, program address:" + Inu                         RL); 126} else {127 System.out.println ("Timed task" "+ JobName +" "+" completed dispatch, program address: "128         + inurl); 129}130} catch (IOException e) {131 e.printstacktrace (); 132 }133 134}135 136}

Define a calling task:

  1 package com.util;  2 3 Import Java.io.BufferedReader;  4 Import Java.io.File;  5 Import java.io.FileNotFoundException;  6 Import Java.io.FileReader;  7 Import java.io.IOException;  8 Import java.util.ArrayList; 9 Import Java.util.HashMap; Ten import Java.util.Iterator; Import java.util.List; Import Java.util.Map; Import Java.util.Map.Entry; Org.apache.log4j.Logger import; org.springframework.beans.factory.annotation.Autowired import; + Import Org.springframework.beans.factory.annotation.Qualifier; Import Com.util.vo.QuartzVo; Com.whalin.MemCached.MemCachedClient import;  22 23/** 24 * Call task * @ClassName: Callquartz * TODO * @author xingle * @date 2014-8-14 12:48:44 29 * * public class Callquartz {to private static Logger Logger = Logger.getlogger (callquartz.class); @Au Towired @Qualifier ("Memcachedclient") a private memcachedclient memclient; Notoginseng public void Callallquartz () {38        List<quartzvo> list =new arraylist<quartzvo> (); iterator<string> iditer = QuartzVo.quartzMap.keySet (). Iterator (); Idstr String = ""; while (Iditer.hasnext ()) {idstr = Idstr+iditer.next () + ","; The former tasks are: "+idstr); String flag = ""; map<string,list<quartzvo> > Map = this.getnewjobs (); Iterator<entry<string, list<quartzvo>>> iter = Map.entryset (). Iterator ();             (Iter.hasnext ()) {entry<string, list<quartzvo>> Entry = Iter.next (); 50 Flag = Entry.getkey (); Wuyi list = Entry.getvalue ();  52} 53//Add New if ("1". Equals (flag)) {Logger.info ("number of newly added scheduled tasks:" "+list.size () +" ");     =0;i<list.size (int i (); i++) {Quartzvo vo = List.get (i); QuartzVo.quartzMap.put (Vo.getjobtitle (), VO); Quartzmanager.addjob (Vo.getjobtitle (), Vo, Vo.getjobcron ()); ("2". Equals (flag)) {logger. Info ("Number of Scheduled Tasks removed:" "+list.size () +" ");             for (int i =0;i<list.size (); i++) {Quartzvo vo = List.get (i); Quartzmanager.removejob (Vo.getjobtitle ()); QuartzVo.quartzMap.remove (Vo.getjobtitle ());      69} 70 71} 72 73} 74 75/** 76 * Get task * @return 78 * @author xingle * @data 2014-8-14 pm 12:59:58 */Bayi private map<string, list<quartzvo>> g Etnewjobs () {82//return MAP map<string,list<quartzvo>> returnmap=new HASHMAP&LT;STRING,LIST&L T Quartzvo>> (); list<quartzvo> returnls = new arraylist<> (); 85//File list list<quartzvo> Filels= new Arraylist<> (); list<string> filenamels = new arraylist<> (); BufferedReader ins = null; The file F = new file ("D:\\test/tasklist1.txt"); The try {quartzvo.id++ int i = = = = = = = = = = = = = = N; Der (f)); 94 String line = "";  Ins.readline (line = ()) = NULL) {96//increase one to perform the identity, 0 not performed//line = Line+ "|"; 98 string[] task = Line.split ("\\|"); Quartzvo Quartzvo = new Quartzvo () 101 String id = "Quarzjob_" + i;1 Quartzvo.setid (ID); 103 quartzvo.setjobtitle (task[0]); 104 QUARTZVO.SETJC                 Allpath (task[1]); Quartzvo.setjobcron (task[2]); 106 quartzvo.sets_date (task[3]); 107               Quartzvo.setcycle (Task[4]); 108 109  Filels.add (QUARTZVO); Filenamels.add (Quartzvo.getjobtitle ()); 111}112 Ins.close (); 113} catch (FileNotFoundException e) {e.printstacktrace ( ); IOException} catch (e) {e.printstacktrace (); 117}118 119 String FLA        g = ""; FileNum int = filels.size (), 121 int quarznum = QuartzVo.quartzMap.size (), 122 if (FileNum > Q Uarznum) {123 flag = "1"; 124 for (int i =0;i<filenum;i++) {quartzvo = Filevo = f Ilels.get (i); 126 if (!                     QuartzVo.quartzMap.keySet (). Contains (Filevo.getjobtitle ())) {127 QuartzVo.quartzList.add (Filevo); 128 To increase the 129 returnls.add (Filevo); 130}131}132}13 3 else if (filenum<quarznum) {134 flag = "2"; 135 for (int i = 0;i<quartzvo.quartzlist.sIze (); i++) {136 if (!filenamels.contains (QuartzVo.quartzList.get (i). Getjobtitle ())) {137//need to be deleted             In addition to the task 138 Returnls.add (QuartzVo.quartzList.get (i)); 139}140}141                 for (int i = 0;i<quartzvo.quartzlist.size (); i++) {142 Quartzvo Vo = QuartzVo.quartzList.get (i); 143 for (int j = 0;j<returnls.size (); j + +) {144 if (Vo.getid (). Equals (Returnls.get (j). GetId ())             ) {145 QuartzVo.quartzList.remove (i); 146}147}148 }149}150 151 returnmap.put (flag, RETURNLS); return returnmap;153}154 155}

Task management:

 1 package com.util; 2 3 Import java.text.ParseException; 4 Import Java.text.SimpleDateFormat; 5 Import Java.util.Date; 6 7 Import Org.apache.log4j.Logger; 8 Import Org.quartz.CronTrigger; 9 Import org.quartz.jobdetail;10 Import org.quartz.scheduler;11 import org.quartz.schedulerexception;12 Import ORG.QUARTZ.SCHEDULERFACTORY;13 Import org.quartz.simpletrigger;14 Import org.quartz.impl.stdschedulerfactory;15 16 Import com.util.vo.quartzvo;17 18 19/**20 * Task management * @ClassName: QUARTZMANAGER22 * @author Xingle24 * @date 201 4-8-14 pm 2:34:1625 */26 public class Quartzmanager {private static Logger Logger = Logger.getlogger (Quartzmanager. Class);//create an uninitialized stdschedulerfactory.30 private static schedulerfactory SF = new Stdsche      Dulerfactory (); private static String Trigger_group_name = "Quartztrigger"; 33 34/**35 * Add Task 36 * @param jobName37 * @param job38 * @param time39 * @author xingle40 * @data 2014-8-14 pm 7:45:0941 */42 public static void AddJob (String jobname,quartzvo job,string time) {43             try {Scheduler Scheduler = Sf.getscheduler (); 45 46//Task Name, Task Group, task execution Class 47 Jobdetail jobdetail = new Jobdetail (JobName, JobName, Job.getclass ()), if ("1". Equals (Job.getcycle ()) ) {//cycle Crontrigger trigger = new Crontrigger (JobName, jobName); Wuyi trigger.setcronexpress                 Ion (Time), Scheduler.schedulejob (Jobdetail, Trigger),}54 else{//single 55 String s_date = Job.gets_date (); Logger.debug ("* * * * * * * * * * * * * * * * * +s_date)", SimpleDateFormat formate= new Sim Pledateformat ("Yyyy-mm-dd HH:mm:ss");    The Date startTime = Formate.parse (s_date); Logger.debug ("* * * * * Time:" +starttime); Simpletrigger trigger = new Simpletrigger (jobName , JobName, StartTime); Scheduler.schedulejob (Jobdetail, Trigger);             }64 if (!scheduler.isshutdown ()) {Scheduler.start (); 66}67 Logger.debug ("*********" Add "Timed Task" "+jobname+" "Load complete! "); catch (Schedulerexception e) {e.printstacktr      Ace (); parseexception} catch (e) {e.printstacktrace (); 74}75}76 77/**78  * Delete Task JobName80 * @param * @author xingle81 * @data 2014-8-14 pm 7:45:1682 */83 public static void Removejob (String jobName) {n-try {Scheduler sched = Sf.getscheduler (); SCHED.P Ausetrigger (jobname,jobname);//Stop Trigger Sched.unschedulejob (jobname,jobname);//Remove Trigger Sched.delete          Job (JobName, JobName); (schedulerexception e) {e.printstacktrace (); 91}92 Logger.Debug ("********* timed Task" "+jobname+" "Deleted complete! "); 93}94 95}

The task read is simply the following:

Task 1|http://www.baidu.com|0 0/1 * * *? | | 1
Task 4|http://www.iteye.com/problems/99952| |2014-08-15 11:34:15|2
Task 5|https://pomotodo.com/app/|0 0/1 * * *? | | 1
Task 3|http://www.w3school.com.cn/html5/|0 0/1 * * *? | | 1
Task 6|http://tool.oschina.net/apidocs/apidoc?api=jdk-zh|0 0/2 * * *? | | 1

Where the Cron trigger time settings can refer to the content configuration, the above tasks can be name can not be duplicated, the task can be added and deleted at any time. Execution result (intercept): Delete Task 3

Examples of Java multithreading--quartz timing scheduling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.