Code example for ScheduledThreadPoolExecutor

Methods: getCorePoolSize, scheduleAtFixedRate, setMaximumPoolSize

0
 
        getScheduledThreadPoolExecutorDaemonThread(); 
        timerTask = new EPLTimerTask(timerCallback);
 
        // With no delay start every internal 
        ScheduledFuture<?> future = timer.scheduleAtFixedRate(timerTask, 0, msecTimerResolution, TimeUnit.MILLISECONDS);
        timerTask.setFuture(future);
    } 
 
    public final void stopInternalClock(boolean warnIfNotStarted)
    { 
        if (timer == null)
        { 
            if (warnIfNotStarted)
            { 
                log.warn(".stopInternalClock Internal clock is already stopped, start first before stopping, operation not completed");
            } 
            return; 
        } 
 
        if (log.isDebugEnabled())
        { 
            log.debug(".stopInternalClock Stopping internal clock daemon thread");
        } 
 
        timer.shutdown();
 
        try 
        { 
            // Sleep for 100 ms to await the internal timer 
            Thread.sleep(100);
        } 
        catch (InterruptedException e)
        { 
            log.info("Timer start wait interval interruped");
        } 
 
        timer = null;
    } 
 
 
    public void enableStats() { 
		if (timerTask != null) {
			timerTask._enableStats = true;
		} 
    } 
 
    public void disableStats() { 
		if (timerTask != null) {
			timerTask._enableStats = false;
			// now it is safe to reset stats without any synchronization 
			timerTask.resetStats();
		} 
    } 
 
    public long getMaxDrift() { 
        return timerTask._maxDrift;
    } 
 
    public long getLastDrift() { 
        return timerTask._lastDrift;
    } 
 
    public long getTotalDrift() { 
        return timerTask._totalDrift;
    } 
 
    public long getInvocationCount() { 
        return timerTask._invocationCount;
    } 
 
   	private void getScheduledThreadPoolExecutorDaemonThread() { 
		timer = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
			// set new thread as daemon thread and name appropriately 
			public Thread newThread(Runnable r) {
                String uri = engineURI;
                if (engineURI == null)
                { 
                    uri = "default";
                } 
                Thread t = new Thread(r, "com.espertech.esper.Timer-" + uri + "-" + id);
				//t.setDaemon(true); 
				return t;
			} 
		}); 
		timer.setMaximumPoolSize(timer.getCorePoolSize());
	} 
 
    private static final Log log = LogFactory.getLog(TimerServiceImpl.class);
}