Use the timer quartz in the SSH & amp; Nutz framework

Source: Internet
Author: User

Use the timer quartz in the SSH & Nutz framework
This article introduces the use of quartz in two frameworks.

First, download the quartz-1.6.0.jar shelf package and add it to the lib directory.

1. Use a timer in the Nutz framework
1. Create a Schedule class:
Package com. xxx. xxx. mail. timer; import org. nutz. ioc. loader. annotation. iocBean; import org. quartz. cronTrigger; import org. quartz. jobBuilder; import org. quartz. jobDetail; import org. quartz. scheduler; import org. quartz. schedulerException; import org. quartz. schedulerFactory; import org. quartz. impl. stdSchedulerFactory;/*** email timer ** @ author ywx **/@ IocBeanpublic class MailSchedule {SchedulerFactory sf = null; SC Hed‑sched = null; JobDetail job = null;/*** start timer */public void startSchedule () {sf = new StdSchedulerFactory (); try {sched = sf. getScheduler (); job = JobBuilder. newJob (MailJob. class ). build (); CronTrigger cTrigger = new MailCronTrigger (). cronTrigger; sched. scheduleJob (job, cTrigger); sched. start ();} catch (SchedulerException e) {e. printStackTrace () ;}/ *** stop timer */public void shutdownSchedule () {if (null ! = Sched) {try {sched. shutdown () ;}catch (SchedulerException e) {e. printStackTrace ();}}}}

2. Write the tasks that need to be done at the scheduled time:
Package com. xxx. xxx. mail. timer; import java. util. calendar; import java. util. date; import org. nutz. ioc. ioc; import org. nutz. ioc. impl. nutIoc; import org. nutz. ioc. loader. combo. comboIocLoader; import org. nutz. log. log; import org. nutz. log. logs; import org. quartz. job; import org. quartz. jobExecutionContext; import org. quartz. jobExecutionException; import com. xxx. xxx. at. meetingAt; import com. xxx. util. mailUtils; import com. xxx. util. propertyUtils;/*** timer execution task content * @ author ywx **/public class MailJob implements Job {Ioc ioc = null; private Log logger = Logs. get (); private MailUtils mailUtils = null; /*** obtain the current Date of the week * @ param time Current Date * @ return * @ throws Exception */public static String isFriday (Date time) {Calendar c = Calendar ar. getInstance (); c. setTime (time); int dayForWeek = 0; if (c. get (Calendar. DAY_OF_WEEK) = 1) {dayForWeek = 7;} else {dayForWeek = c. get (Calendar. DAY_OF_WEEK)-1;} return String. valueOf (dayForWeek);} @ SuppressWarnings ("static-access") @ Overridepublic void execute (JobExecutionContext arg0) throws JobExecutionException {// when it is marked as "0, task timer does not start if ("0 ". equals (PropertyUtils. getProperty ("emaiTimerFlag") {logger.info ("timer Job not started"); return;} logger.info ("timer Job started"); try {if (ioc = null) {ioc = new NutIoc (new ComboIocLoader ("* org. nutz. ioc. loader. json. jsonLoader "," ioc/"," * org. nutz. ioc. loader. annotation. annotationIocLoader "," com. wonders ");} if (mailUtils = null) {mailUtils = ioc. get (MailUtils. class); // put the "meeting topic" of this reminder email in the following method (MeetingAt. getMeetingIds () // mailUtils. sendbatch (MailUtils. getFromPerson (), MailUtils. addToperson (), "", ""); // mailUtils. sendbatch (MailUtils. getFromPerson (), MailUtils. addToperson (), MeetingAt. getMeetingIds (); // send mailUtils. bactchSendPrompt (MailUtils. getFromPerson (), MailUtils. addToperson (), MailUtils. getAllInfo ();} catch (Exception e) {e. printStackTrace ();} finally {ioc. depose () ;}} public static void main (String args []) {String str [] = PropertyUtils. getProperty ("sendTime "). split ("\ s +"); System. out. println (str [str. length-2]) ;}}

3. When to execute the task:
Package com. xxx. xxx. mail. timer; import org. quartz. cronScheduleBuilder; import org. quartz. cronTrigger; import org. quartz. triggerBuilder; import com. xxx. util. propertyUtils; public class MailCronTrigger {public CronTrigger cronTrigger = null; public MailCronTrigger () {// get the scheduled mail sending time String cron = PropertyUtils. getProperty ("sendTime"); CronScheduleBuilder schedule = CronScheduleBuilder. cronSchedule (cron); cronTrigger = TriggerBuilder. newTrigger (). withSchedule (schedule ). build ();}}

4. After the timer is written, configure the Service Startup Configuration:
Package com. xxx. tiles. extend. setup; import org. nutz. ioc. ioc; import org. nutz. mvc. nutConfig; import org. nutz. mvc. setup; import org. nutz. mvc. annotation. filters; import com.jacb.com. mainSTA; import com. xxx. project. support. timer. projectSchedule; import com. xxx. xxx. mail. timer. mailSchedule; import com. xxx. xxx. support. timer. signSchedule; import com. xxx. tiles. dic. dicConfigManager; @ Filterspublic class ConfigSetup implements Setup {public void init (NutConfig nc) {Ioc ioc = nc. getIoc (); // start the email timer MailSchedule mailSchedule = ioc. get (MailSchedule. class); mailSchedule. startSchedule ();} public void destroy (NutConfig nc) {Ioc ioc = nc. getIoc (); // stop the email timer MailSchedule mailSchedule = ioc. get (MailSchedule. class); mailSchedule. shutdownSchedule ();}}

5. Added to the MainModule class of Nutz. function: Enable the timer when starting the service.
@SetupBy(ConfigSetup.class)


Example:
@ IocBy (type = ComboIocProvider. class, args = {"* org. nutz. ioc. loader. json. jsonLoader "," ioc/"," * org. nutz. ioc. loader. annotation. annotationIocLoader "," com. wonders "}) @ Modules (scanPackage = true) @ SetupBy (ConfigSetup. class) @ Filters ({@ By (type = SessionFilter. class, args = {"/index"}) @ AdaptBy (type = SearchTableAdaptor. class) @ Fail ("ioc: errView") public class MainModule {Code omitted... }
Note: The above example is so simple and practical ......
Ii. Using the timer in the SSH framework should be simpler and clearer than using the timer in Nutz. Do not write CronTrigger and Schedule; you can use either of the following methods (one of the methods described in this article is sufficient ).
1. Configure the listening quartz in web. xml:
         
  
   org.quartz.ee.servlet.QuartzInitializerListener
   
 

2. Add the quartz_jobs.xml file and add the job node information to the configuration file:
<! -- {Cke_protected} {C} % 3C! % 2D % 2D % 3 Fxml % 20 version % 3D % 221.0% 22% 20 encoding % 3D % 22gb2312% 22% 3F % 2D % 2D % 3E --> <quartz> <job> <id> 1 </id> <description> regularly sends SMS messages every 30 minutes) send once </description> <job-detail> <name> J1 </name> <group> DEFAULT </group> <job-class> com. xxxx. tiles. sms. task. timerSendJob </job-class> </job-detail> <trigger> <cron> <name> T1 </name> <group> DEFAULT </group> <job-name> j1 </job-name> <job-group> DEFAULT </job-group> <cron-expr Ession> 0 1/30 ***? </Cron-expression> </cron> </trigger> </job> <id> 2 </id> <description> data reconciliation at each day </description> <job-detail> <name> J2 </name> <group> DEFAULT </group> <job-class> com. xxxx. xxxx. xxxx. factory. dataChecking </job-class> </job-detail> <trigger> <cron> <name> T2 </name> <group> DEFAULT </group> <job-name> j2 </job-name> <job-group> DEFAULT </job-group> <cron-expression> 0 35 13? ** </Cron-expression> </cron> </trigger> </job> <id> 3 </id> <description> heartbeat packet is completed at every day., purpose: monitor whether the service is running normally. </description> <job-detail> <name> J3 </name> <group> DEFAULT </group> <job-class> com. xxxx. xxxx. dj. factory. dataCheckClear </job-class> </job-detail> <trigger> <cron> <name> T3 </name> <group> DEFAULT </group> <job-name> j3 </job-name> <job-group> DEFAULT </job-group> <cron-expression> 0 0 12 **? </Cron-expression> </cron> </trigger> </job> </quartz>
3. timed business methods:
Package com. xxx. xxx. xxx. factory; import java. SQL. connection; import java. SQL. preparedStatement; import java. SQL. resultSet; import java. SQL. SQLException; import java. util. date; import org. apache. log4j. logger; import org. quartz. job; import org. quartz. jobExecutionContext; import org. quartz. jobExecutionException; import org. springframework. beans. factory. annotation. autowired; import org. springframework. context. applicationContext; import org. springframework. stereotype. component; import org. springframework. transaction. annotation. transactional; import anlr. collections. list; import com. xxx. core. utils. dateUtils; import com. xxx. core. utils. springContextHolder; import com. xxx. xxx. dj. dao. dataSendingDao; import com. xxx. xxx. dj. entity. dataSending; import com. xxx. xxx. dj. service. receiveService; import com. xxx. xxx. dj. service. sendMessageService;/*** data reconciliation, regularly send data

* // @ Component @ Transactional public class DataChecking implements Job {@ Autowired private SendMessageService sendMessageService; @ Autowired private DataSendingDao dataSendingDao; private static final String FAIL_FLAG = "0 "; /** log */private Logger logger = Logger. getLogger (DataChecking. class); @ Override public void execute (JobExecutionContext arg0) throws JobExecutionException {// obtain the context Applicat IonContext ctx = SpringContextHolder. getApplicationContext (); ReceiveService receiveService = ctx. getBean (ReceiveService. class); // orgName and password are obtained from the government affairs hall. The statistical start time and end time are configured in application, and json is obtained in service. long startSend = System. currentTimeMillis (); logger.info ("=========== [data reconciliation start] Start =========="); System. out. println ("data reconciliation start time:" + DateUtils. date2String (new Date (), DateUtils. FORMAT_DATETIME); String result = Exploreservice. getResult ("XXXXXXX (unit name)", "123456"); logger.info ("=========== data reconciliation result: "+ result +" =========================== "); logger.info ("=========== [data reconciliation start] End-total cost [" + (System. currentTimeMillis ()-startSend) + "] millisecond =========="); // result (Y: sent successfully, N: Failed ). // if ("N ". equals (result) {this. updateDataZwdt2shzz () ;}}/*** update the data corresponding to the exdata_processing ing table error information of the front-end server to the xxxxxxx database as a tag. */public void updateDataZwd T2shzz () {// ====== query the front-end server error information table exdata_receiving ======= Connection conn = sendMessageService. getZwdtConnection (); PreparedStatement pstmt = null; ResultSet rs = null; String SQL = "SELECT ST_MEMO FROM [exdata]. [dbo]. [exdata_indexing ing] WHERE ST_MEMO is not null "; try {pstmt = conn. prepareStatement (SQL); rs = pstmt.exe cuteQuery (); while (rs. next () {// get error message content String content = rs. getString (1); // capture the first serial number ID S Tring nmSeqId = content. substring (0, content. indexOf ("SHSTSH"). trim (); String hql = "from DataSending d where d. nmSeqId =? "; DataSending dataSending = null; java. util. List DataSendingList = dataSendingDao. find (hql, Integer. parseInt (nmSeqId); for (int I = 0; I
Note: compared with the Nutz framework, it is much easier to use a timer in ssh.
 

Related Article

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.