Use of the Spring2.5.6 timer

Source: Internet
Author: User
Tags object object set time string format xmlns ticket

The timer was recently used in the work, and the project was using SSH, so consider using spring's timer to implement the function, but after understanding the requirements, spring's simpletriggerbean and Crontriggerbean are not satisfied. The requirements are:

1.3 timers are required to check the encrypted fields of 2 data tables at a specific time. If the sensitive data of the database is found to have been modified (not the same as the encrypted field), a warning data is generated for the modified data to be saved to the system warning table, in the background management system, The administrator can deal with it in time. The check field of the modified data is also changed to false. For maintenance personnel to query data.

2. First timer: Start daily 2 o'clock in the morning and check the data from 2 o'clock in the morning to 2 o'clock in the morning today.

3. Second timer: Every 2 days, 2:10 minutes, check the data 2 days before 2 o'clock in the morning to today 2 o'clock in the morning.

4. Third timer: Every 3 days, 2:20 minutes, check the data 3 days before 2 o'clock in the morning to today 2 o'clock in the morning.

5. It is necessary to ensure that each record is checked 3 times during the 3 timer cycle. When examining data, avoid creating too many objects in the database lock table and code, querying only the first 100 records at a time, verifying 100 data after checking the last ID and avoiding duplicate checking.

When using Crontriggerbean to do, you can use the expression of cronexpression to configure every few days in a few seconds a few milliseconds to run, but later found that the cronexpression expression ' days ' parameters, from the monthly number 1th is calculated, Instead of counting from the day the server started, the 3rd timer will be executed less once a month is only 30 days or 29 days.

With simpletriggerbean words, in the online search configuration, the entire big talk is Ctrl+c,ctrl+v said Startdelay and Repeatinterval configuration and use. Because the server startup time is uncertain, Therefore, the delay time for the first execution cannot be configured here.

2 kinds of triggers are not, all can only meet part of the demand, so went to see the spring time task of the source code. And then I have a train of thought, Simpletriggerbean can configure the cycle of each timer loop execution, So as long as the 3 timer to determine the first execution time can be configured on the line, so that a custom class, inherit Simpletriggerbean, define the parameters of the configuration, and then rewrite the Setstarttime method, the problem can be resolved. Here's the code:

Configuration of XML:

<?xml version= "1.0" encoding= "UTF-8"?>
<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xsi:schemalocation=" Http://www.springframework.org/schema/beans/http Www.springframework.org/schema/beans/spring-beans-2.5.xsd "default-autowire=" No "default-lazy-init=" false ">
<!--Scheduled Tasks--
<bean id= "Scheduler" class= "Org.springframework.scheduling.quartz.SchedulerFactoryBean" >
<property name= "Triggers" >
<list>
<ref bean= "Checkticketandacl24trigger"/>
<ref bean= "Checkticketandacl48trigger"/>
<ref bean= "Checkticketandacl72trigger"/>
</list>
</property>
</bean>

<!--task Scheduling class--
<bean id= "Checkticketandacctcreditlog" class= "Com.ct.spade.gs.core.task.CheckTicketAndAcctCreditLog" >
<property name= "Generichibernatedao" ref= "Generichibernatedao"/>
<property name= "JdbcTemplate" ref= "JdbcTemplate"/>
</bean>
<!--24-hour Check 1 times--
<bean id= "CheckTicketAndAcctCreditLog24" class= " Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean ">
<property name= "TargetObject" ref= "Checkticketandacctcreditlog"/>
<property name= "Targetmethod" value= "execute24hrs"/>
</bean>
<bean id= "Checkticketandacl24trigger" class= "Com.ct.spade.gs.core.task.CustomSimpleTriggerBean" >
<property name= "Jobdetail" ref= "CheckTicketAndAcctCreditLog24"/>
<property name= "Checktimevalue" value= "2"/>
<property name= "Delayexpression" value= "1 2 0 0 0"/>
<property name= "Repeatinterval" value= "86400000"/><!--Run once a day--
</bean>

<!--48-hour Check 1 times--
<bean id= "checkTicketAndAcctCreditLog48" class= " Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean ">
<property name= "TargetObject" ref= "Checkticketandacctcreditlog"/>
<property name= "Targetmethod" value= "execute48hrs"/>
</bean>
<bean id= "Checkticketandacl48trigger" class= "Com.ct.spade.gs.core.task.CustomSimpleTriggerBean" >
<property name= "Jobdetail" ref= "checkTicketAndAcctCreditLog48"/>
<property name= "Checktimevalue" value= "2"/>
<property name= "Delayexpression" value= "2 2 0 0"/>
<property name= "Repeatinterval" value= "172800000"/>
</bean>

<!--72-hour Check 1 times--
<bean id= "checkTicketAndAcctCreditLog72" class= " Org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean ">
<property name= "TargetObject" ref= "Checkticketandacctcreditlog"/>
<property name= "Targetmethod" value= "execute72hrs"/>
</bean>
<bean id= "Checkticketandacl72trigger" class= "Com.ct.spade.gs.core.task.CustomSimpleTriggerBean" >
<property name= "Jobdetail" ref= "checkTicketAndAcctCreditLog72"/>
<property name= "Checktimevalue" value= "2"/>
<property name= "Delayexpression" value= "3 2 0 0"/>
<property name= "Repeatinterval" value= "259200000"/>
</bean>

</beans>

The Customsimpletriggerbean class is a class that defines its own inheritance Simpletriggerbean. Checktimevalue is the point of judgment, such as when the server startup time exceeds the setting for this time, Then the time for the first run of the scheduled task starts tomorrow. Delayexpression expression has 5 parameters separated by a space, respectively, the time of day and minute milliseconds, representing the timing of the first run of the task, the parameter ' days ' is the server started the day after the delay of a few days, The next 4 parameters are the specific set time, 5 parameters can be any one, each parameter has a default value, the following paste Customsimpletriggerbean code:

Java Code:

Import java.io.Serializable;
Import Java.util.Calendar;
Import Java.util.Date;


Import Org.springframework.scheduling.quartz.SimpleTriggerBean;


Import Com.ct.spade.gs.core.randomiser_v2.util.StringUtil;
Import Com.ct.spade.gs.core.utils.ArrayUtils;

/**

* Custom Trigger start time

*/
public class Customsimpletriggerbean extends Simpletriggerbean implements Serializable {

Private static final long serialversionuid = 2049345814989743480L;
Hours
private static final int hour_of_day = 0;
Minutes
private static final int MINUTE = 1;
Seconds
private static final int SECOND = 2;
Milliseconds
private static final int millisecond = 3;

The first time unit to delay execution of judgment (default: Calendar.hour_of_day= days)
private int checktimetype;
The time value of the first deferred execution judgment
private int checktimevalue;
Time expression for first execution (format: ' Day_of_month hour_of_day MINUTE SECOND millisecond ')
Private String delayexpression;

@Override
public void Setstarttime (Date startTime) {
Calendar calendar = Calendar.getinstance ();
Calendar.settime (New Date ());
int checktime = Calendar.get (Gettimetype (Getchecktimetype ()));
if (checktime >= this.checktimevalue) {
Setstartuptime (Calendar);
}
Super.setstarttime (Calendar.gettime ());
}

/**
* Set the start time
* @param Startcalendar
*/
private void Setstartuptime (Calendar startcalendar) {
if (null = = Startcalendar) {
Return
}
if (! Stringutil.isnotempty (delayexpression)) {
delayexpression = "1 0 0 0 0";
}
Delayexpression = Delayexpression.trim (). ReplaceAll ("\\s+", "" ");
string[] timevalues = Delayexpression.split ("");
if (Arrayutils.isempty (timevalues)) {
Startcalendar.set (Calendar.day_of_month, Startcalendar.get (calendar.day_of_month) + 1);
Startcalendar.set (calendar.hour_of_day, 0);
Startcalendar.set (calendar.minute, 0);
Startcalendar.set (Calendar.second, 0);
Startcalendar.set (Calendar.millisecond, 0);
} else {
int[] Intarrays = Arrayutils.tointarray (timevalues);
int length = Arrayutils.length (intarrays);
if (length > 0) {
Startcalendar.set (Calendar.day_of_month, Startcalendar.get (calendar.day_of_month) + intArrays[0]);
}
if (length > 1) {
Startcalendar.set (Calendar.hour_of_day, intarrays[1]);
} else {
Startcalendar.set (Calendar.hour_of_day, Startcalendar.get (Calendar.hour_of_day));
}
if (length > 2) {
Startcalendar.set (Calendar.minute, intarrays[2]);
} else {
Startcalendar.set (Calendar.minute, Startcalendar.get (Calendar.minute));
}
if (length > 3) {
Startcalendar.set (Calendar.second, intarrays[3]);
} else {
Startcalendar.set (Calendar.second, Startcalendar.get (Calendar.second));
}
if (length > 4) {
Startcalendar.set (Calendar.millisecond, intarrays[4]);
} else {
Startcalendar.set (Calendar.millisecond, Startcalendar.get (Calendar.millisecond));
}
}
}

/**
* Get Time type
* @param delaytype
* @return
*/
private int Gettimetype (int delaytype) {
int result = 0;
Switch (delaytype) {
Case Hour_of_day:
result = Calendar.hour_of_day;
Break
Case MINUTE:
result = Calendar.minute;
Break
Case SECOND:
result = Calendar.second;
Break
Case millisecond:
result = Calendar.millisecond;
Break
Default:
Break
}
return result;
}

public int Getchecktimevalue () {
return checktimevalue;
}

public void Setchecktimevalue (int checktimevalue) {
This.checktimevalue = Checktimevalue;
}

public int Getchecktimetype () {
return checktimetype;
}

public void Setchecktimetype (int checktimetype) {
This.checktimetype = Checktimetype;
}

Public String getdelayexpression () {
return delayexpression;
}

public void Setdelayexpression (String delayexpression) {
This.delayexpression = delayexpression;
}
}

Checkticketandacctcreditlog class: This class is specific to the execution of the business, the business code is not posted, the Execute method is implemented according to the requirements.

Import Java.text.SimpleDateFormat;
Import java.util.ArrayList;
Import Java.util.Calendar;
Import Java.util.Date;
Import java.util.List;

Import Org.framework.support.hibernate.GenericHibernateDao;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import Org.springframework.jdbc.core.JdbcTemplate;
Import org.springframework.transaction.annotation.Transactional;

public class Checkticketandacctcreditlog {

Private Logger Logger = Loggerfactory.getlogger (Checkticketandacctcreditlog.class);

Private final static String Check_time = "2:00:00.000";
Private final static String format_date = "YYYY-MM-DD";
Private final static String Format_time = "Yyyy-mm-dd HH:mm:ss. SSS ";

Private Generichibernatedao Generichibernatedao;
Private JdbcTemplate JdbcTemplate;

/**
* 24 Hours execution time
*/
public void execute24hrs () {
Logger.info (getDateString (New Date (), format_time) + "24H quartz check Start");

Date nowdate = new Date ();
String startTime = getdatebeforestring (nowdate, 1) + "" + check_time;
String endTime = getdatestring (nowdate, format_date) + "" + check_time;

Execute (startTime, endTime);

Logger.info (getDateString (New Date (), format_time) + "24H quartz check finished");
}

/**
* 48 Hours execution Time
*/
public void execute48hrs () {
Logger.info (getDateString (New Date (), format_time) + "48H quartz check Start");

Date nowdate = new Date ();
String startTime = getdatebeforestring (nowdate, 2) + "" + check_time;
String endTime = getdatestring (nowdate, format_date) + "" + check_time;

Execute (startTime, endTime);

Logger.info (getDateString (New Date (), format_time) + "48H quartz check finished");
}

/**
* 72 Hours execution Time
*/
public void execute72hrs () {
Logger.info (getDateString (New Date (), format_time) + "72H quartz check Start");

Date nowdate = new Date ();
String startTime = getdatebeforestring (nowdate, 3) + "" + check_time;
String endTime = getdatestring (nowdate, format_date) + "" + check_time;

Execute (startTime, endTime);

Logger.info (getDateString (New Date (), format_time) + "72H quartz check finished");
}

@Transactional
public void execute (string startTime, String endTime) {
// ...
}

/**
* Search Acctcreditlog First 100 records according to the conditions
*
* @param LastID
* ID
* @param startTime
* Start time
* @param endTime
* End Time
* @return
*/
Private list< acctcreditlog > findacctcreditloglist (Long LastID, String startTime, String endTime) {
if (LastID < 0) {
return null;
}

//...
return null;
}

/**
* Check ticket Top 100 records
*
* @param LastID
* Last ID of each round
* @param startTime
* Start time
* @param endTime
* End Time
* @return
*/
Private list< Ticket > findticketlist (Long LastID, String startTime, String endTime) {
if (LastID < 0) {
return null;
}
// ...
return null;
}

/**
* Save or update data in bulk
*
* @param dataList
*/
Private Boolean batchsaveorupdate (string[] sql) {
Boolean flag = true;

//...

return flag;

}

Private Warningdata Buildwarningdata (string msgtype, Long ID, string merchant, string player, String ClientIP, String gam Ecode, string currency, string fingerprint) {
Warningdata warningdata = new Warningdata ();
// ...

return warningdata;
}


/**
* Verify that encrypted fields are the same
*
* @param acctcreditlog
* @return
*/
Private Boolean Isequalssha512str (Object object) {
if (null = = object) {
return false;
}
Boolean flag = false;
//...
return flag;
}

/**
* Gets the string representation of the time
*
* @param date
* @return
*/
Private String getdatestring (date date, String format) {
return new SimpleDateFormat (format). format (date);
}

/**
* Gets the string representation of the days before the specified date
*
* @param date
* Date Specified
* @param before
* Forward for a few days
* @return
*/
Private String getdatebeforestring (date date, int before) {
if (before <= 0) {
return getdatestring (date, format_date);
}
Calendar calendar = Calendar.getinstance ();
Calendar.settime (date);
Calendar.set (Calendar.date, Calendar.get (calendar.date)-before);
Return getDateString (Calendar.gettime (), format_date);
}

public void Setgenerichibernatedao (Generichibernatedao Generichibernatedao) {
This.generichibernatedao = Generichibernatedao;
}

public void Setjdbctemplate (JdbcTemplate jdbctemplate) {
This.jdbctemplate = JdbcTemplate;
}
}

The purpose of writing this blog is to fear that there will be a period of time without this knowledge point, may forget. Some implementations of the code may have a better way of implementing it, if any of the great gods see mercy.


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.