开发者

how to invoke schedular every day

开发者 https://www.devze.com 2023-03-22 17:52 出处:网络
what i do is ,when i run first time a servlet (which is invoked from jsp) that while put an entry of that service,daily in conf file.i want to run a scheduler which will invoke program(servlet- which

what i do is ,when i run first time a servlet (which is invoked from jsp) that while put an entry of that service,daily in conf file.i want to run a scheduler which will invoke program(servlet- which runs and send mail) for that service daily 10 .

below is the code i use to execute a task.but problem is when i stop the server ,the scheduler stops and nothing happens

public class Schedule
{
    public static final String CONF_PATH = "../webapps/selen/WEB-INF/scheduling.properties";
    public static Properties schProps = null;
    public static FileInputStream sis = null;
    public static long period;
    public static Timer timer = new Timer();
    public static String servicename = null;
    public static String keyValues = null;
    public static String reValues[] = null;
    public static String schedulingValue = null;
    public static String service_url = null;
        public static String browserlist = null;
        public static String testType = null;
    public static String mailCheacked = null;
        public static String toaddr = null;
    public stat开发者_运维问答ic HttpServletRequest request = null;
    public static HttpServletResponse response = null;
    public static String serversURL = null;
    public static String contextPath = null;
        public static Date delay = null;
    public void scheduleLoad(String serviceValue) throws Exception
    {
        try
            {
            schProps = new Properties();
            sis = new FileInputStream(CONF_PATH);
            schProps.load(sis);
            servicename = SServlet.serviceName; 
            keyValues = schProps.getProperty(serviceValue);
            reValues = keyValues.split(",");
            String request = reValues[0];
            String response = reValues[1];
            schedulingValue = reValues[2];
            service_url = reValues[3];
            browserlist = reValues[4];
            testType = reValues[5];
            mailCheacked = reValues[6];
            toaddr = reValues[7];
            serversURL = reValues[8];
            contextPath = reValues[9];
            if(reValues[2].equals("Daily"))
            {

                Calendar cal =Calendar.getInstance();
                cal.set(Calendar.HOUR,10);
                cal.set(Calendar.MINUTE,20);
                cal.set(Calendar.SECOND,0);
                delay = cal.getTime();
                period = 1000 * 60 * 60 * 24;
                schedule();
            }
            else if(reValues[2].equals("Stop"))
            {
                stop();
            }   
        }
        catch(NullPointerException npe)
        {
            System.out.println("null point exception ");
        }
        finally
        {
            if(sis !=null)
            {
                sis.close();
            }
        }           

    }
    public static void schedule()
    {
        MyTimerTask mt = new MyTimerTask(request,response,servicename,service_url,browserlist,mailCheacked,testType,schedulingValue,toaddr,serversURL,contextPath);
        timer.schedule(mt,delay,period);
    }
    public static void stop()
    {
        timer.cancel();
    }

} 
class MyTimerTask extends TimerTask
{
    public HttpServletRequest request;
    public HttpServletResponse response;    
    public String servicename;
    public String service_url;
    public String browserlist;
    public String mailCheacked;
    public String testType;
    public String schedulingValue;
    public String toaddr;
    public String serversURL;
    public String contextPath;
    public MyTimerTask(HttpServletRequest request,HttpServletResponse response, String servicename,String service_url,String browserlist,String mailCheacked,String testType,String schedulingValue,String toaddr,String serversURL, String contextPath)
    {
        this.request = request;
        this.response = response;
        this.servicename = servicename;
        this.service_url = service_url;
        this.browserlist = browserlist;
        this.mailCheacked = mailCheacked;
        this.testType = testType;
        this.schedulingValue = schedulingValue;
        this.toaddr = toaddr;
        this.serversURL = serversURL;
        this.contextPath = contextPath;
    }
    public void run()
    {
        SServlet sservlet = new SServlet();
        sservlet.sServerloading(request,response,servicename,service_url,browserlist,mailCheacked,testType,schedulingValue,toaddr,false,1,serversURL,contextPath);
    }
}


The JDK Timer runs in the JVM, not in the operating system. It's not CRON or Windows scheduler. So when you stop your server (Tomcat? JBoss? Glassfish?), you are effectivly stopping the JVM that the Timer lives in so of course it won't run any more. If you want a timer (scheduler) that runs independently of your server, you will have to start it in it's own JVM, either as a standalone java program using the java command or inside another server instance.

On a side note, if you're open to some critique, a small review of your code:

  • Avoid mixing static and non-static contexts if possible. Your Schedule class instance method scheduleLoad() makes heavy use of static member variables for statefull storage. Variables are either only used in the execution of a method (in which case they should be declared inside that method) or they are used to describe the state of an object (in which case they should be private instance members of the class) or they are global constants or immutable global variables (in which case they should be declared static final). Exceptions to these exist, but are less common.

  • Avoid declaring member variables public if they are not also final. Adhere to the JavaBean pattern, use getters and setters. If a variable is, in reality, a constant then it should be public static final.

  • Avoid using classes or parameters out of scope. For instance, your MyTimerTask uses HttpServletRequest and HttpServletResponse as member variables and method parameters. This makes no sense as MyTimerTask is not used in the scope of a servlet request (and will subsequently always be null, right?). Or, if that is indeed the case, if you are explicitly setting the static members of the Schedule in some servlet and then invoking scheduleLoad(), see my first point about improper use of static context. Your code would not be thread-safe and concurrent invocation of whichever servlet that uses the Schedule would produce unpredictable behaviour.

UPDATE: It's hard to know where to start as I'm not sure what your level of expertise is in Java. If you are unfamiliar with how to execute stand-alone java applications, I would suggest having a go at some tutorials. Oracle has a bunch at http://download.oracle.com/javase/tutorial/. http://download.oracle.com/javase/tutorial/getStarted/index.html is a good place to start as it walks you through a very basic "hello world" type application with a main method and how to execute it using the java command, as well as some common mistakes and problems.

Once you've figured all that out, take a few minutes to figure out what your application should do, which resources it will require and if it needs to call any "external" systems. You mentioned that it should "execute a servlet to send mail". Does that mean that it has to call a specific servlet or is it just the sending mail that is really what you are after. In that case, maybe you can just move all the mail sending logic to your standalone program? If not, you will have to call the servlet using a http request (like a browser would). There are a number of existing frameworks for doing things like that. Apache HttpClient is a very popular one.


If you stop program it does not work. It is not a bug. It is a feature. BTW if you shutdown your computer nothing happens too :).

But If you questing is how to make my scheduled task more robust, e.g. how to make task to continue working when server stops and then starts again you have to persist somewhere the state of you scheduler, i.e. in your case the last time of task execution. You can implement this yourself: create special file and store the data there. You can use cross platform pure java Preferences API to do this: the data will be stored in file system in Unix and Registry in windows. you can save state in DB too.

But you can use other products that have already implemented this functionality. The most popular and well-known is Quartz.

But Quartz still need some java process to be up and running. If you want to be able to run your tasks even if no java process is running use platform dependent tools: cron tab for Unix and scheduler API for windows (it is accessible via VBScript, JScript, command line). Unix has cron

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号