Java计时器任务出现意外行为

时间:2015-03-25 11:46:06

标签: java timer scheduled-tasks

我的计时器任务无法正常运行。我已安排它每隔3秒重复一次特定任务,但这种情况不会发生。

根据Java文档:

  

计划(TimerTask任务,长延迟,长期)。   在指定的延迟之后开始,为重复的固定延迟执行安排指定的任务。随后的执行大约以规定的时间间隔进行,并按指定的时间段分开。

public class Tester {

    public static void main(String[] args) {    
        log.info("Schedule task");
        Timer time = new Timer();

        TesterClient tc = new TesterClient();
        time.schedule(tc, 0, 3000);
    }
}


public class TesterClient extends TimerTask {
    public void init() {
        System.out.println("New Task!!!!");
    }
    @Override
    public void run() {
        init();
    }
}

但我只得到一个"新任务!!!!"在控制台中打印

我在这里错过了什么吗?

由于

更新:

我将尝试在此处粘贴相关的每段代码,并在执行方面从上到下进行。

开始:

public class Tester {

    public static Logger log = Logger.getLogger("com.orderlysoftware.orderlycalls.manager.ManagerClient");
    public static Timer time = new Timer();

    public static void main(String[] args) {            
        log.info("Creating service");
        Service.serviceInit();  

        log.info("Initializing TesterClient for scheduled task");
        TesterClient tc = new TesterClient();
        time.schedule(tc, 0, 3000);
    }
    public static ManagerSettings managerSettings() {
        ManagerSettings managerSettings = new ManagerSettings();
        managerSettings.setName("managerClient");
        managerSettings.setHost("77.237.251.152");
        managerSettings.setPort(5038);
        managerSettings.setUsername("orderlystats");
        managerSettings.setPassword("orderlystats");

        return managerSettings;
    }   
}

Service class method:

static ExecutorService executorService; 
    {
        serviceInit();
    }

    //public static ClassLoader loader;

    public static void serviceInit(){
        if(executorService!=null) {
            return;
        }
        executorService= Executors.newCachedThreadPool();
        try {
            ThreadPoolExecutor tpe=(ThreadPoolExecutor)executorService;
            tpe.setMaximumPoolSize(100000);
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }

package com.orderlysoftware.testing;

import java.io.IOException;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.logging.Logger;

import com.orderlysoftware.orderlycalls.OrderlyCalls;
import com.orderlysoftware.orderlycalls.asterisk.manager.ManagerClient;
import com.orderlysoftware.orderlycalls.asterisk.manager.action.ManagerResponse;
import com.orderlysoftware.orderlycalls.asterisk.manager.event.ManagerEvent;
import com.orderlysoftware.orderlycalls.asterisk.manager.event.ManagerEventListener;
import com.orderlysoftware.orderlycalls.base.Service;

public class TesterClient extends TimerTask {

    public static Logger log = Logger.getLogger("com.orderlysoftware.orderlycalls.manager.ManagerClient");
    public static ExecutorService es = Service.getExecutorService();

    public ManagerClient mc;

    public void init() {    
        log.info("run check method to see if Manager Client is running");
        boolean running = check();

        log.info("checker status is : " + running);
        while(running) {
            try {
                Thread.sleep(3000);
                startCall();
            } catch (InterruptedException e) {
                log.info("Sleep interrupted");
            }
        }   
    }
    public boolean check() {
        log.info("ManagerClient is: " + mc);
        if(mc == null) {
            log.info("Initialize service");
            mc = (ManagerClient)OrderlyCalls.createService(ManagerClient.class, Tester.managerSettings());
            log.info("Initialize ManagerClient");
            mc.init();
            log.info("Service created. ManagerClient initialized : "+ mc);
        }
        if(!mc.isConnected()) {
            log.info("ManagerClient is not connected");         
            return false;
        }
        log.info("Check if ManagerClient is connected AND running");
        if(mc.isConnected() && !mc.isRunning()) {
            log.info("Manager Client is connected but NOT running");
            return false;
        }
        if(mc.isConnected() && mc.isRunning()) {
            log.info("ManagerClient is connected and running");
            return true;
        }
        return false;
    }
    private void startCall() {
        log.info("Adding listener to the call");
        addListenerToCall(mc);

        int testID = 0;
        ManagerResponse response = null;
        try {
            response = mc.originate("Local/1001@main", "1001", "main", "1", null, null, 2500, "1002", "testID=" + (testID++), "1", true);
            log.info("Manager response is: " + response);
            if(response == null) {
                mc.shutdown();
                throw new IOException("Null response for originate.");              
            }
            if(!response.getValue("Response").equals("Success")) {
                mc.shutdown();
                throw new IOException("Originate returned " + response.getValue("Response") + ": " + response.getValue("Message"));
            }
        } catch (IOException e) {
            log.info("IO Exception" + e.toString());
        }
    }   
    public void addListenerToCall(ManagerClient mc) {       
        try {
            // Add event listener 
            log.info("Adding ManagerEventListener to ManagerClient: " + mc);
            mc.addManagerEventListener(new ManagerEventListener() {         
                @Override
                public void handleManagerEvent(ManagerEvent event) {
                    if("OriginateResponse".equals(event.getType())) {
                        handleOriginateResponse(event);
                    }
                }
            });
        } catch (IOException e) {
            log.info("IO Exception : " + e);
        }       
    }
    protected void handleOriginateResponse(ManagerEvent event) {
        try {
            // do something here 
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            log.info("sleep interupted" + e);
        }           
    }

    @Override
    public void run() {
        log.info("New Task!!!!!!!!!!");
        init(); 
    }   
}

2 个答案:

答案 0 :(得分:3)

它适用于我 - 但我怀疑问题是你让Timer收集了垃圾:

  

在对Timer对象的最后一次实时引用消失并且所有未完成的任务都已完成执行之后,计时器的任务执行线程正常终止(并且变为垃圾回收)。但是,这可能会发生任意长的时间。

如评论中所述,我相信“未完成的任务”意味着“已经启动的任务”,而不仅仅是“将被安排的任务”。然而,文档还不清楚,我可能会弄错。

如果你阻止垃圾收集(例如通过在静态变量中保留对Timer的引用),那么我认为你会看到它永远存在......

答案 1 :(得分:0)

你的程序也适合我。该问题在您的计划中发生以下变更后再现:

import java.util.*;
public class Tester {

    public static void main(String[] args) {
        System.out.println("Schedule task");
        Timer time = new Timer();

        TesterClient tc = new TesterClient();
        time.schedule(tc, 0, 3000);
    }
}


class TesterClient extends TimerTask {
    public void init() {
        System.out.println("New Task!!!!");
    }
    @Override
    public void run() {
        init();
        this.cancel(); //-------This causes hang in execution after printing once
    }
}

但是,不确定在程序中没有cancel()会导致这种情况发生的原因。