2017年5月26日
package org.gdharley.activiti.integration.rest;
import com.fasterxml.jackson.annotation.jsonproperty;
import com.fasterxml.jackson.databind.jsonnode;
import com.fasterxml.jackson.databind.objectmapper;
import org.activiti.engine.activitiexception;
import org.activiti.engine.delegate.delegateexecution;
import org.activiti.engine.delegate.expression;
import org.activiti.engine.delegate.javadelegate;
import org.apache.commons.lang3.stringutils;
import org.apache.http.httpresponse;
import org.apache.http.namevaluepair;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.uribuilder;
import org.apache.http.client.utils.urlencodedutils;
import org.apache.http.conn.ssl.sslconnectionsocketfactory;
import org.apache.http.conn.ssl.sslcontextbuilder;
import org.apache.http.conn.ssl.trustselfsignedstrategy;
import org.apache.http.entity.stringentity;
import org.apache.http.impl.client.closeablehttpclient;
import org.apache.http.impl.client.httpclientbuilder;
import org.apache.http.message.basicnamevaluepair;
import org.apache.http.protocol.http;
import org.apache.http.util.entityutils;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.http.httpmethod;
import java.io.ioexception;
import java.net.uri;
import java.net.urisyntaxexception;
import java.util.list;
/**
* created by gharley on 5/2/17.
*/
public class simplerestdelegate implements javadelegate {
private static final logger logger = loggerfactory.getlogger(simplerestdelegate.class);
protected expression endpointurl;
protected expression httpmethod;
protected expression issecure;
protected expression payload;
// 一个content-type是application/json的请求,具体看起来是这样的:
// post /some-path http/1.1
// content-type: application/json
//
// { "foo" : "bar", "name" : "john" }
//
//
// { "foo" : "bar", "name" : "john" } 就是这个请求的payload
protected expression headers;
protected expression responsemapping;
protected objectmapper objectmapper = new objectmapper();
// create a mixin to force the basicnamevaluepair constructor
protected static abstract class basicnamevaluepairmixin {
private basicnamevaluepairmixin(@jsonproperty("name") string name, @jsonproperty("value") string value) {
}
}
public void execute(delegateexecution execution) throws exception {
logger.info("started generic rest call delegate");
if (endpointurl == null || httpmethod == null) {
throw new illegalargumentexception("an endpoint url and http method are required");
}
string resturl = getexpressionasstring(endpointurl, execution);
string payloadstr = getexpressionasstring(payload, execution);
string headersjson = getexpressionasstring(headers, execution); // [{"name":"headername", "value":"headervalue"}]
string method = getexpressionasstring(httpmethod, execution);
string rmapping = getexpressionasstring(responsemapping, execution);
string secure = getexpressionasstring(issecure, execution);
string scheme = secure == "true" ? "https" : "http";
// validate uri and create create request
uri restendpointuri = composeuri(resturl, execution);
logger.info("using generic rest uri " restendpointuri.tostring());
httprequestbase httprequest = createhttprequest(restendpointuri, scheme, method, headersjson, payloadstr, rmapping);
// create http client
closeablehttpclient httpclient = createhttpclient(httprequest, scheme, execution);
// execute request
httpresponse response = executehttprequest(httpclient, httprequest);
// map response to process instance variables
if (responsemapping != null) {
mapresponse(response, rmapping, execution);
}
logger.info("ended generic rest call delegate");
}
protected uri composeuri(string resturl, delegateexecution execution)
throws urisyntaxexception {
uribuilder uribuilder = null;
uribuilder = encodepath(resturl, uribuilder);
return uribuilder.build();
}
protected uribuilder encodepath(string resturl, uribuilder uribuilder) throws urisyntaxexception {
if (stringutils.isnotempty(resturl)) {
// check if there are url params
if (resturl.indexof('?') > -1) {
list params = urlencodedutils.parse(new uri(resturl), "utf-8");
if (params != null && !params.isempty()) {
resturl = resturl.substring(0, resturl.indexof('?'));
uribuilder = new uribuilder(resturl);
uribuilder.addparameters(params);
}
} else {
uribuilder = new uribuilder(resturl);
}
}
return uribuilder;
}
protected httprequestbase createhttprequest(uri restendpointuri, string scheme, string httpmethod, string headers, string payload, string responsemapping) {
if (stringutils.isempty(httpmethod)) {
throw new activitiexception("no http method provided");
}
if (restendpointuri == null) {
throw new activitiexception("no rest endpoint uri provided");
}
httprequestbase httprequest = null;
httpmethod parsedmethod = httpmethod.valueof(httpmethod.touppercase());
stringentity input;
uribuilder builder = new uribuilder(restendpointuri);
switch (parsedmethod) {
case get:
try {
httprequest = new httpget(builder.build());
httprequest = addheaderstorequest(httprequest, headers);
} catch (urisyntaxexception use) {
throw new activitiexception("error while building get request", use);
}
break;
case post:
try {
httprequest = new httppost(builder.build());
input = new stringentity(payload);
// input.setcontenttype(new basicheader(http.content_type, "application/json"));
((httppost) httprequest).setentity(input);
httprequest = addheaderstorequest(httprequest, headers);
break;
} catch (exception e) {
throw new activitiexception("error while building post request", e);
}
case put:
try {
httprequest = new httpput(builder.build());
input = new stringentity(payload);
// input.setcontenttype(new basicheader(http.content_type, "application/json"));
((httpput) httprequest).setentity(input);
httprequest = addheaderstorequest(httprequest, headers);
break;
} catch (exception e) {
throw new activitiexception("error while building put request", e);
}
case delete:
try {
httprequest = new httpdelete(builder.build());
httprequest = addheaderstorequest(httprequest, headers);
} catch (urisyntaxexception use) {
throw new activitiexception("error while building delete request", use);
}
break;
default:
throw new activitiexception("unknown http method provided");
}
return httprequest;
}
protected closeablehttpclient createhttpclient(httprequestbase request, string scheme, delegateexecution execution) {
sslconnectionsocketfactory sslsf = null;
// allow self signed certificates and hostname mismatches.
if (stringutils.equalsignorecase(scheme, "https")) {
try {
sslcontextbuilder builder = new sslcontextbuilder();
builder.loadtrustmaterial(null, new trustselfsignedstrategy());
sslsf = new sslconnectionsocketfactory(builder.build(), sslconnectionsocketfactory.allow_all_hostname_verifier);
} catch (exception e) {
logger.warn("could not configure http client to use ssl", e);
}
}
httpclientbuilder httpclientbuilder = httpclientbuilder.create();
if (sslsf != null) {
httpclientbuilder.setsslsocketfactory(sslsf);
}
return httpclientbuilder.build();
}
protected httpresponse executehttprequest(closeablehttpclient httpclient, httprequestbase httprequest) {
closeablehttpresponse response = null;
try {
response = httpclient.execute(httprequest);
} catch (ioexception e) {
throw new activitiexception("error while executing http request: " httprequest.geturi(), e);
}
if (response.getstatusline().getstatuscode() >= 400) {
throw new activitiexception("error while executing http request " httprequest.geturi() " with status code: "
response.getstatusline().getstatuscode());
}
return response;
}
protected void mapresponse(httpresponse response, string responsemapping, delegateexecution execution) {
if (responsemapping == null || responsemapping.trim().length() == 0) {
return;
}
jsonnode jsonnode = null;
try {
string jsonstring = entityutils.tostring(response.getentity());
jsonnode = objectmapper.readtree(jsonstring);
} catch (exception e) {
throw new activitiexception("error while parsing response", e);
}
if (jsonnode == null) {
throw new activitiexception("didn't expect an empty response body");
}
execution.setvariable(responsemapping, jsonnode.tostring());
}
protected httprequestbase addheaderstorequest(httprequestbase httprequest, string headerjson) {
boolean contenttypedetected = false;
if (headerjson != null) {
// convert json to array
try {
// configuration for jackson/fasterxml
objectmapper.addmixinannotations(basicnamevaluepair.class, basicnamevaluepairmixin.class);
namevaluepair[] headers = objectmapper.readvalue(headerjson, basicnamevaluepair[].class);
for (namevaluepair header : headers) {
httprequest.addheader(header.getname(), header.getvalue());
if (header.getname().equals(http.content_type)) {
contenttypedetected = true;
}
}
} catch (exception e) {
throw new activitiexception("unable to parse json header array", e);
}
}
// now add content type if necessary
if (!contenttypedetected) {
httprequest.addheader(http.content_type, "application/json");
}
return httprequest;
}
/**
* @return string value of expression.
* @throws {@link illegalargumentexception} when the expression resolves to a value which is not a string
* or if the value is null.
*/
protected string getexpressionasstring(expression expression, delegateexecution execution) {
if (expression == null) {
return null;
} else {
object value = expression.getvalue(execution);
if (value instanceof string) {
return (string) value;
} else {
throw new illegalargumentexception("expression does not resolve to a string or is null: " expression.getexpressiontext());
}
}
}
}
posted @ 华梦行 阅读(212) | |
2016年5月7日
1. quickstart
the cron4j main entity is the scheduler. with a instance you can execute tasks at fixed moments, during all the year. a scheduler can execute a task once a minute, once every five minutes, friday at 10:00, on february the 16th at 12:30 but only if it is saturday, and so on.
the use of the cron4j scheduler is a four steps operation:
- create your scheduler instance.
- schedule your actions. to schedule an action you have to tell the scheduler what it has to do and when. you can specify what using a java.lang.runnable or a instance, and you can specify when using a scheduling pattern, which can be represented with a string or with a instance.
- starts the scheduler.
- stops the scheduler, when you don't need it anymore.
consider this simple example:
import it.sauronsoftware.cron4j.scheduler; public class quickstart { public static void main(string[] args) { // creates a scheduler instance. scheduler s = new scheduler(); // schedule a once-a-minute task. s.schedule("* * * * *", new runnable() { public void run() { system.out.println("another minute ticked away..."); } }); // starts the scheduler. s.start(); // will run for ten minutes. try { thread.sleep(1000l * 60l * 10l); } catch (interruptedexception e) { ; } // stops the scheduler. s.stop(); } }
this example runs for ten minutes. at every minute change it will print the sad (but true) message "another minute ticked away...".
some other key concepts:
- you can schedule how many tasks you want.
- you can schedule a task when you want, also after the scheduler has been started.
- you can change the scheduling pattern of an already scheduled task, also while the scheduler is running (reschedule operation).
- you can remove a previously scheduled task, also while the scheduler is running (deschedule operation).
- you can start and stop a scheduler how many times you want.
- you can schedule from a file.
- you can schedule from any source you want.
- you can supply listeners to the scheduler in order to receive events about the executed task.
- you can control any ongoing task.
- you can manually launch a task, without using a scheduling pattern.
- you can change the scheduler working time zone.
- you can validate your scheduling patterns before using them with the scheduler.
- you can predict when a scheduling pattern will cause a task execution.
2. scheduling patterns
a unix crontab-like pattern is a string split in five space separated parts. each part is intended as:
- minutes sub-pattern. during which minutes of the hour should the task been launched? the values range is from 0 to 59.
- hours sub-pattern. during which hours of the day should the task been launched? the values range is from 0 to 23.
- days of month sub-pattern. during which days of the month should the task been launched? the values range is from 1 to 31. the special value "l" can be used to recognize the last day of month.
- months sub-pattern. during which months of the year should the task been launched? the values range is from 1 (january) to 12 (december), otherwise this sub-pattern allows the aliases "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov" and "dec".
- days of week sub-pattern. during which days of the week should the task been launched? the values range is from 0 (sunday) to 6 (saturday), otherwise this sub-pattern allows the aliases "sun", "mon", "tue", "wed", "thu", "fri" and "sat".
the star wildcard character is also admitted, indicating "every minute of the hour", "every hour of the day", "every day of the month", "every month of the year" and "every day of the week", according to the sub-pattern in which it is used.
once the scheduler is started, a task will be launched when the five parts in its scheduling pattern will be true at the same time.
scheduling patterns can be represented with instances. invalid scheduling patterns are cause of s. the schedulingpattern class offers also a static method, that can be used to validate a string before using it as a scheduling pattern.
some examples:
5 * * * *
this pattern causes a task to be launched once every hour, at the begin of the fifth minute (00:05, 01:05, 02:05 etc.).
* * * * *
this pattern causes a task to be launched every minute.
* 12 * * mon
this pattern causes a task to be launched every minute during the 12th hour of monday.
* 12 16 * mon
this pattern causes a task to be launched every minute during the 12th hour of monday, 16th, but only if the day is the 16th of the month.
every sub-pattern can contain two or more comma separated values.
59 11 * * 1,2,3,4,5
this pattern causes a task to be launched at 11:59am on monday, tuesday, wednesday, thursday and friday.
values intervals are admitted and defined using the minus character.
59 11 * * 1-5
this pattern is equivalent to the previous one.
the slash character can be used to identify step values within a range. it can be used both in the form */c and a-b/c. the subpattern is matched every c values of the range 0,maxvalue or a-b.
*/5 * * * *
this pattern causes a task to be launched every 5 minutes (0:00, 0:05, 0:10, 0:15 and so on).
3-18/5 * * * *
this pattern causes a task to be launched every 5 minutes starting from the third minute of the hour, up to the 18th (0:03, 0:08, 0:13, 0:18, 1:03, 1:08 and so on).
*/15 9-17 * * *
this pattern causes a task to be launched every 15 minutes between the 9th and 17th hour of the day (9:00, 9:15, 9:30, 9:45 and so on... note that the last execution will be at 17:45).
all the fresh described syntax rules can be used together.
* 12 10-16/2 * *
this pattern causes a task to be launched every minute during the 12th hour of the day, but only if the day is the 10th, the 12th, the 14th or the 16th of the month.
* 12 1-15,17,20-25 * *
this pattern causes a task to be launched every minute during the 12th hour of the day, but the day of the month must be between the 1st and the 15th, the 20th and the 25, or at least it must be the 17th.
finally cron4j lets you combine more scheduling patterns into one, with the pipe character:
0 5 * * *|8 10 * * *|22 17 * * *
this pattern causes a task to be launched every day at 05:00, 10:08 and 17:22.
3. how to schedule, reschedule and deschedule a task
the simplest manner to build a task is to implement the well-known java.lang.runnable interface. once the task is ready, it can be scheduled with the . method. this method throws an when the supplied string does not represent a valid scheduling pattern.
another way to build a task is to extend the abstract class, which is more powerful and let the developer access some other cron4j features. this is better discussed in the "" paragraph. task instances can be scheduled with the and the methods.
scheduling methods available in the scheduler always return an id used to recognize and retrieve the scheduled operation. this id can be used later to reschedule the task (changing its scheduling pattern) with the or the methods, and to deschedule the task (remove the task from the scheduler) with the method.
the same id can also be used to retrieve the scheduling pattern associated with a scheduled task, with the method, or to retrieve the task itself, with the method.
4. how to schedule a system process
system processes can be easily scheduled using the class:
processtask task = new processtask("c:\\windows\\system32\\notepad.exe"); scheduler scheduler = new scheduler(); scheduler.schedule("* * * * *", task); scheduler.start(); // ...
arguments for the process can be supplied by using a string array instead of a single command string:
string[] command = { "c:\\windows\\system32\\notepad.exe", "c:\\file.txt" }; processtask task = new processtask(command); // ...
environment variables for the process can be supplied using a second string array, whose elements have to be in the name=value form:
string[] command = { "c:\\tomcat\\bin\\catalina.bat", "start" }; string[] envs = { "catalina_home=c:\\tomcat", "java_home=c:\\jdks\\jdk5" }; processtask task = new processtask(command, envs); // ...
the default working directory for the process can be changed using a third parameter in the constructor:
string[] command = { "c:\\tomcat\\bin\\catalina.bat", "start" }; string[] envs = { "catalina_home=c:\\tomcat", "java_home=c:\\jdks\\jdk5" }; file directory = "c:\\mydirectory"; processtask task = new processtask(command, envs, directory); // ...
if you want to change the default working directory but you have not any environment variable, the envs parameter of the constructor can be set to null:
processtask task = new processtask(command, null, directory);
when envs is null the process inherits every environment variable of the current jvm:
environment variables and the working directory can also be set by calling the and methods.
the process standard output and standard error channels can be redirected to files by using the and methods:
processtask task = new processtask(command, envs, directory); task.setstdoutfile(new file("out.txt")); task.setstderrfile(new file("err.txt"));
in a siminal manner, the standard input channel can be read from an existing file, calling the method:
processtask task = new processtask(command, envs, directory); task.setstdinfile(new file("in.txt"));
5. how to schedule processes from a file
the cron4j scheduler can also schedule a set of processes from a file.
you have to prepare a file, very similar to the ones used by the unix crontab, and register it in the scheduler calling the method. the file can be descheduled by calling the method. scheduled files can be retrieved by calling the method.
scheduled files are parsed every minute. the scheduler will launch every process declared in the file whose scheduling pattern matches the current system time.
syntax rules for cron4j scheduling files are reported in the "" paragraph.
6. building your own task
a java.lang.runnable object is the simplest task ever possible, but to gain control you need to extend the class. in the plainest form, implementing runnable or extending task are very similar operations: while the first requires a run() method, the latter requires the implementation of . the execute(taskexecutioncontext) method provides a instance, which the runnable.run() method does not provide. the context can be used in the following ways:
a task can communicate with its executor, by notifying its internal state with a textual description. this is called status tracking. if you are interested in supporting status tracking in your task, you have to override the method, which should return true. once this has been done, within the execute(taskexecutioncontext) method you are enabled to call the context method. this will propagate your task status message to its executor. the status message, through the executor, can be retrieved by an external user (see the "" paragraph).
a task can communicate with its executor, by notifying its completeness level with a numeric value. this is called completeness tracking. if you are interested in supporting completeness tracking in your task, you have to override the method, which should return true. once this has been done, within the execute(taskexecutioncontext) method you are enabled to call the context method, with a value between 0 and 1. this will propagate your task completeness level to its executor. the completeness level, through the executor, can be retrieved by an external user (see the "" paragraph).
a task can be optionally paused. if you are interested in supporting pausing and resuming in your task, you have to override the method, which should return true. once this has been done, within the execute(taskexecutioncontext) method you have to periodically call the context method. this will pause the task execution until it will be resumed (or stopped) by an external user (see the "" paragraph).
a task can be optionally stopped. if you are interested in supporting stopping in your task, you have to override the method, which should return true. once this has been done, within the execute(taskexecutioncontext) method you have to periodically call the context method. this will return true when the execution has be demanded to be stopped by an external user (see the "" paragraph). then it's your responsibility to handle the event, by letting your task gently stop its ongoing activities.
through the context, the task can retrieve the scheduler, calling .
through the context, the task can retrieve its executor, calling .
a custom task can be , or returned by a .
7. building your own collector
you can build and plug within the scheduler your own task source, via the task collector api.
the cron4j scheduler supports the registration of one or more instances, with the method. registered collectors can be retrieved with the scheduler method. a previously registered collector can be removed from the scheduler with the method. collectors can be added, queried or removed at every moment, also when the scheduler is started and it is running.
each registered task collector is queried by the scheduler once a minute. the scheduler calls the collector method. the implementation must return a instance. a tasktable is a table that associates tasks and scheduling patterns. the scheduler, once the table has been retrieved, will examine the reported entries, and it will execute every task whose scheduling pattern matches the current system time.
a custom collector can be used to tie the scheduler with an external task source, i.e. a database or a xml file, which can be managed and changed in its contents also at run time.
8. building your own scheduler listener
the api can be used to listen to scheduler events.
the schedulerlistener interface requires the implementation of the following methods:
this one is called every time a task is launched by the scheduler.
this one is called every time a task execution has been successfully completed.
this one is called every time a task execution fails due to an uncaught exception.
see the "" paragraph for more info about task executors.
once your schedulerlistener instance is ready, you can register it on a scheduler object by calling its method. already registered listeners can be removed by calling the method. the scheduler can also give back any registered listener, with the method.
schedulerlisteners can be added and removed at every moment, also while the scheduler is running.
9. executors
the scheduler, once it has been started and it is running, can be queried to give back its executors. an executor is similar to a thread. executors is used by the scheduler to execute tasks.
by calling the . method you can obtain the currently ongoing executors.
you can also obtain an executor through a instance (see the "" paragraph).
each executor, represented by a instance, performs a different task execution.
the task can be retrieved with the method.
the executor status can be checked with the method: it returns true if the executor is currently running.
if the executor is running, the current thread can be paused until the execution will be completed, calling the method.
the method returns true if the currently executing task supports status tracking. it means that the task communicates to the executor its status, represented by a string. the current status message can be retrieved by calling the executor method.
the method returns true if the currently executing task supports completeness tracking. it means that the task communicates to the executor its own completeness level. the current completeness level can be retrieved by calling the executor method. returned values are between 0 (task just started and still nothing done) and 1 (task completed).
the method returns true if the currently executing task supports execution pausing. it means that the task execution can be paused by calling the executor method. the pause status of the executor can be checked with the method. a paused executor can be resumed by calling its method.
the method returns true if the currently executing task supports execution interruption. it means that the task execution can be stopped by calling the executor method. the interruption status of the executor can be checked with the method. stopped executors cannot be resumed.
the method returns a time stamp reporting the start time of the executor, or a value less than 0 if the executor has not been yet started.
the method returns the scheduler which is the owner of the executor.
the method returns a textual guid for the executor.
executors offer also an event-driven api, through the class. a taskexecutorlistener can be added to a taskexecutor with its method. listeners can be removed with the method, and they can also be retrieved with the method. a taskexecutorlistener must implement the following methods:
called when the executor is requested to pause the ongoing task. the given parameter represents the source taskexecutor instance.
called when the executor is requested to resume the execution of the previously paused task. the given parameter represents the source taskexecutor instance.
called when the executor is requested to stop the task execution. the given parameter represents the source taskexecutor instance.
called when the executor has completed the task execution. the first parameter represents the source taskexecutor instance, while the second is the optional exception that has caused the task to be terminated. if the task has been completed successfully, the given value is null.
called every time the execution status message changes. the first parameter represents the source taskexecutor instance, while the second is the new message issued by the task.
called every time the execution completeness value changes. the first parameter represents the source taskexecutor instance, while the second is the new completeness value (between 0 and 1) issued by the task.
10. manual task launch
if the scheduler is started and running, it is possible to manually launch a task, without scheduling it with a pattern. the method is .. the task will be immediately launched, and a instace is returned to the caller. the returned object can be used to control the task execution (see the "" paragraph).
11. working with time zones
scheduler instances, by default, work with the system default time zone. i.e. a scheduling pattern whose value is 0 2 * * * will activate its task at 02:00 am according to the default system time zone. the scheduler can be requested to work with a different time zone, which is not the system default one. call . and . to control this feature.
once the default time zone has been changed, system current time is adapted to the supplied zone before comparing it with registered scheduling patterns. the result is that any supplied scheduling pattern is treated according to the specified time zone. suppose this situation:
- system time: 10:00
- system time zone: gmt 1
- scheduler time zone: gmt 3
the scheduler, before comparing system time with patterns, translates 10:00 from gmt 1 to gmt 3. it means that 10:00 becomes 12:00. the resulted time is then used by the scheduler to activate tasks. so, in the given configuration at the given moment, any task scheduled as 0 12 * * * will be executed, while any 0 10 * * * will not.
12. daemon threads
the java virtual machine exits when the only threads running are all daemon threads. the cron4j scheduler can be configured to spawn only daemon threads. to control this feature call the . method. this method must be called before the scheduler is started. default value is false. to check the scheduler current daemon status call the . method.
13. predictor
the class is able to predict when a scheduling pattern will be matched.
suppose you want to know when the scheduler will execute a task scheduled with the pattern 0 3 * jan-jun,sep-dec mon-fri. you can predict the next n execution of the task using a predictor instance:
string pattern = "0 3 * jan-jun,sep-dec mon-fri"; predictor p = new predictor(pattern); for (int i = 0; i < n; i ) { system.out.println(p.nextmatchingdate()); }
14. cron parser
the class can be used to parse crontab-like formatted file and character streams.
if you want to schedule a list of tasks declared in a crontab-like file you don't need the cronparser, since you can do it by adding the file to the scheduler, with the . method.
consider to use the cronparser if the scheduler.schedulefile(file) method is not enough for you. in example, you may need to fetch the task list from a remote source which is not representable as a java.io.file object (a document on a remote server, a dbms result set and so on). to solve the problem you can implement your own , getting the advantage of the cronparser to easily parse any crontab-like content.
you can parse a whole file/stream, but you can also parse a single line.
a line can be empty, can contain a comment or it can be a scheduling line.
a line containing no characters or a line with only space characters is considered an empty line.
a line whose first non-space character is a number sign (#) is considered a comment.
empty lines and comment lines are ignored by the parser.
any other kind of line is parsed as a scheduling line.
a valid scheduling line respects the following structure:
scheduling-pattern [options] command [args]
- scheduling-pattern is a valid scheduling pattern, according with the definition given by the class.
- options is a list of optional information used by cron4j to prepare the task execution environment. see below for a more detailed description.
- command is a system valid command, such an executable call.
- args is a list of optional arguments for the command.
after the scheduling pattern item, other tokens in each line are space separated or delimited with double quotation marks (").
double quotation marks delimited items can take advantage of the following escape sequences:
- \" - quotation mark
- \\ - back slash
- \/ - slash
- \b - back space
- \f - form feed
- \n - new line
- \r - carriage return
- \t - horizontal tab
- \ufour-hex-digits - the character at the given unicode index
the options token collection can include one or more of the following elements:
- in:file-path - redirects the command standard input channel to the specified file.
- out:file-path - redirects the command standard output channel to the specified file.
- err:file-path - redirects the command standard error channel to the specified file.
- env:name=value - defines an environment variable in the scope of the command.
- dir:directory-path - sets the path of the working directory for the command. this feature is not supported if the executing jvm is less than 1.3.
it is also possible to schedule the invocation of a method of a java class in the scope of the parser classloader. the method has to be static and it must accept an array of strings as its sole argument. to invoke a method of this kind the syntax is:
scheduling-pattern java:classname#methodname [args]
the #methodname part can be omitted: in this case the main(string[]) method will be assumed.
please note that static methods are invoked within the scheduler same jvm, without spawning any external process. thus in, out, err, env and dir options can't be applied.
invalid scheduling lines are discarded without blocking the parsing procedure, but an error message is sent to the application standard error channel.
valid examples:
0 5 * * * sol.exe 0,30 * * * * out:c:\ping.txt ping 10.9.43.55 0,30 4 * * * "out:c:\documents and settings\carlo\ping.txt" ping 10.9.43.55 0 3 * * * env:java_home=c:\jdks\1.4.2_15 dir:c:\myproject out:c:\myproject\build.log c:\myproject\build.bat "nightly build" 0 4 * * * java:mypackage.myclass#startapplication myoption1 myoption2
posted @ 华梦行 阅读(1953) | |