To parse a timed task cron into Chinese

Source: Internet
Author: User

When using the timer quartz, the cron expression, the boss said that as a development you can read, other non-development colleagues may not understand, to use a way they can understand the expression.

Fortunately our project requires an expression that is not particularly troublesome, so we have written a simplified method of converting to Chinese

Package Com.common.utils;import Java.text.parseexception;import Java.text.simpledateformat;import Java.util.arraylist;import Java.util.calendar;import Java.util.date;import Java.util.list;import Org.quartz.cronexpression;public class cronexpparser{/** * Parse corn expression, generate time series for specified date * * @param cronexpressio n Cron expression * @param crondate cron Parse date * @param result Crom Parse Time series * @return Parse successfully failed */public static Boole An parser (string cronexpression, String crondate, list<string> result) {if (cronexpression = = NULL | | cro Nexpression.length () < 1 | | Crondate = = NULL | |        Crondate.length () < 1) {return false;            } else {cronexpression exp = null;            Initialize the cron expression parser try {exp = new cronexpression (cronexpression); } catch (ParseException e) {//TODO auto-generated catch block E.prin Tstacktrace ();                return false;            }//define the build time range//define start time, 23 points before the previous day 59 minutes 59 seconds Calendar C = calendar.getinstance ();            String Sstart = crondate + "00:00:00";            SimpleDateFormat SDF = new Java.text.SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");            Date dstart = null;            try {dstart = Sdf.parse (Sstart); } catch (ParseException e) {//TODO auto-generated catch block E.prin            Tstacktrace ();            } c.settime (DStart);            C.add (Calendar.second,-1);                        DStart = C.gettime ();            Define end time, 23 points of the day 59 minutes 59 seconds C.add (Calendar.date, 1);                        Date dend = C.gettime ();            Generate time series java.util.Date dd = DStart;            DD = Exp.getnextvalidtimeafter (DD); while ((Dd.gettime () >= dstart.gettime ()) && (Dd.gettime () <= Dend.gettime ())) {Result.add (Sdf.format (DD));            DD = Exp.getnextvalidtimeafter (DD);        } exp = null;    } return true; public static string Translatetochinese (String cronexp) {if (Cronexp = = NULL | | cronexp.length () <        1) {return "cron expression is empty";        } cronexpression exp = null;        Initialize the cron expression parser try {exp = new cronexpression (CRONEXP);        } catch (ParseException e) {return "Corn expression is incorrect";        } string[] Tmpcorns = Cronexp.split ("");        StringBuffer sbuffer = new StringBuffer (); if (tmpcorns.length = = 6) {//Resolve month if (!tmpcorns[4].equals ("*")) {SBu            Ffer.append (Tmpcorns[4]). Append ("month");            } else {sbuffer.append ("monthly"); }//Parse Week if (!tmpcorns[5].equals ("*") &&!tmpcorns[5].equals ("?"))                {char[] Tmparray = Tmpcorns[5].tochararray ();                        for (char tmp:tmparray) {switch (TMP) {                            Case ' 1 ': Sbuffer.append ("Sunday");                        Break                            Case ' 2 ': Sbuffer.append ("Monday");                        Break                            Case ' 3 ': Sbuffer.append ("Tuesday");                        Break                            Case ' 4 ': Sbuffer.append ("Wednesday");                        Break                            Case ' 5 ': Sbuffer.append ("Thursday");                        Break                            Case ' 6 ': Sbuffer.append ("Friday");                        Break Case ' 7 ': sBuFfer.append ("Saturday");                        Break                            Case '-': Sbuffer.append ("to");                        Break                            Default:sBuffer.append (TMP);                    Break            }}}//Parse day if (!tmpcorns[3].equals ("?"))                 {if (!tmpcorns[3].equals ("*")) {Sbuffer.append (tmpcorns[3]). Append ("Day");                } else {sbuffer.append ("daily"); }}//Parse if (!tmpcorns[2].equals ("*")) {Sbuffer.ap            Pend (Tmpcorns[2]). Append ("Time");            } else {sbuffer.append ("every hour"); }//Resolve sub-if (!tmpcorns[1].equals ("*")) {SBUFFER.APpend (Tmpcorns[1]). Append ("min");            } else {sbuffer.append ("per minute"); }//Parse seconds if (!tmpcorns[0].equals ("*")) {Sbuffer.append (tmpcorns [0]).            Append ("seconds");            } else {sbuffer.append ("per second");            }} return sbuffer.tostring ();        }//test method public static void main (string[] args) {String cron_expression = "0 0 3 * *?";        Generates a CRON time series of the specified date String cron_date = "2016-04-26";        System.out.println (cron_expression);                System.out.println (Cronexpparser.translatetochinese (cron_expression));        list<string> ltime = new arraylist<string> (); if (! Cronexpparser.parser (Cron_expression, Cron_date, Ltime)) {System.out.println ("Cannot generate CRON expression: date," +cron_date+ "; non-conforming to rule C        Ron expression: "+cron_expression); } for (int i=0;i<ltime.size (); i++) {        System.out.println (Ltime.get (i)); }    }}

Execution Result:

0 0 3 * *? daily 3:0 0 secs 2016-04-26 03:00:00

The boss said the interface can not directly let them write expressions, it is best to have an intuitive feeling to choose,

So I designed the interface as follows: You can manually modify the execution time, or you can use the Cron expression interface to modify, the execution date modification when the description information will also be modified

<TR><TD align= "Right" >
Execution Time:
</td>
<td>
<input id= "cron" class= "tr180 td26" value= "name=" cron "type=" text "onchange=" Checkcron (); " >
<div > Description: Set Timer schedule Time Table format <b> sec </b> (0-59,*) <b> minutes </b> (0-59,*) <b> </b> (0-23,* ) <b> Day </b> (0-31,*,?) <b> month </b> (0-11) <b> week </b> (1-7,*,? 1=sun)/increment of exponential value <br> Example ①0 0 12 *? Example ②0 15,16 10 15 *? Example ③0 15 10? * 2-6</div>

</td>
</tr>
<tr>
<TD align= "Right" >
Execution Time Description:
</td>
<td>
<div id= "Crondesc" ></div>
</td>
</tr>

  

Using a onchange method, invoking an AJAX can implement the description of the update.

function Checkcron () {var datas={"Cronexp": $ ("#cron"). Val ()}; $.ajax ({type: "post", url: "/getcrondesc", Data:datas, DataType: "Text", success:function (data) {///successful processing function $ ("#cronDesc"). HTML (data);});}

And the Cron expression of the page effect, looking for a long time, finally see what to see. Thanks to the selfless sharing of netizens, on his basis, I changed to change to their own needs, the effect is as follows.

Open a new page

Openwin (".. /.. /static/cron/cronindex.htm ", 640, 480); function Openwin (url,width,height) {var newwin = window.open (URL," _blank "," Scrollbars=yes,resizable=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,top=50,left=120,width= "+width+", height= "+height);}

After selecting a value on the open page, close the child page and assign a value to a form on the parent page, calling a JS method of the parent page

function Selcron () {//Gets the value of the selected selection box var cron = $ ("#cron"). Val (); Window.opener.cron.value=cron;window.close (); Window.opener.checkCron ();}

(PS: Actually do not know how to upload attachments, forget, corn page I will not write, go to find it yourself)

To parse a timed task cron into Chinese

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.