Example usage for java.util TimerTask TimerTask

List of usage examples for java.util TimerTask TimerTask

Introduction

In this page you can find the example usage for java.util TimerTask TimerTask.

Prototype

protected TimerTask() 

Source Link

Document

Creates a new timer task.

Usage

From source file:org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilterTests.java

public void testCallsCleanAllOnSchedule() throws Exception {
    final MethodFlag timerTaskFlag = new MethodFlag();
    final Cas20ProxyReceivingTicketValidationFilter filter = newCas20ProxyReceivingTicketValidationFilter();

    final TimerTask timerTask = new TimerTask() {
        public void run() {
            timerTaskFlag.setCalled();//from  ww w  .  ja v  a  2s . c o  m
        }
    };

    final int millisBetweenCleanUps = 250;
    filter.setProxyGrantingTicketStorage(storage);
    filter.setTimerTask(timerTask);
    filter.setTimer(defaultTimer);
    filter.setMillisBetweenCleanUps(millisBetweenCleanUps);

    filter.init();

    // wait long enough for the clean up to occur
    Thread.sleep(millisBetweenCleanUps * 2);

    assertTrue(timerTaskFlag.wasCalled());
    filter.destroy();
}

From source file:com.perfect.autosdk.core.JsonProxy.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String addr = service.serverUrl + AddressUtil.getJsonAddr(interfaces) + '/' + method.getName();

    JsonConnection conn = new GZIPJsonConnection(addr);
    conn.setConnectTimeout(service.connectTimeoutMills);
    conn.setReadTimeout(service.readTimeoutMills);
    JsonEnvelop request = makeRequest(args[0]);
    conn.sendRequest(request);/*from  www.j av  a  2  s .co  m*/
    JsonEnvelop<ResHeader, ?> response = conn.readResponse(ResHeader.class, method.getReturnType());
    ResHeader resHeader = response.getHeader();
    if (!resHeader.getFailures().isEmpty()) {
        if (log.isErrorEnabled()) {
            log.error("Call Error: Head info = " + resHeader + "\n" + "account info = " + service.getUsername()
                    + "\n" + "request info = " + addr + "\n" + "request param = " + args[0]);
        }
        if (resHeader.getFailures().get(0).getCode() == 8904) {
            Timer timer = new Timer("waitLock");
            final CountDownLatch latch = new CountDownLatch(1);
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("waiting....");
                    latch.countDown();
                }
            }, 15000);

            latch.await();
        }
    }
    ResHeaderUtil.resHeader.set(response.getHeader());
    BaiduApiQuota.setQuota(service.username, response.getHeader().getQuota());
    return response.getBody();
}

From source file:co.mafiagame.telegraminterface.outputhandler.TelegramChannel.java

@PostConstruct
private void init() {
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    client = HttpClients.createDefault();
    this.url = telegramUrl + telegramToken + "/sendMessage";
    TimerTask timerTask = new TimerTask() {
        @Override//  w  w w.  jav a 2 s.c  o  m
        public void run() {
            SendMessage sendMessage = null;
            try {
                if (!outQueue.isEmpty()) {
                    sendMessage = outQueue.take();
                    deliverMessage(sendMessage);
                }
            } catch (InterruptedException e) {
                logger.error("error in reading outQueue", e);
            } catch (Exception e) {
                logger.error("error sending message " + sendMessage, e);
            }
        }
    };
    Timer timer = new Timer();
    timer.schedule(timerTask, TimeUnit.MINUTES.toMillis(1), TimeUnit.MILLISECONDS.toMillis(200));
}

From source file:cycronix.CTandroid.CTAserver.java

/** Called when the activity is first created. */
@Override/* w  w w. j a v  a  2s.  co  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getSettings(); // Restore preferences
    copyAssets(); // copy assets to external storage

    setContentView(R.layout.main);
    statusET = (EditText) findViewById(R.id.myText);
    if (statusET != null)
        statusET.setText("Not Started.");
    statusET.setEnabled(false);
    myipET = (EditText) findViewById(R.id.myIP);
    if (myipET != null)
        myipET.setText(getIPAddress(true));
    myipET.setEnabled(false);
    counterET = (EditText) findViewById(R.id.Counter);
    counterET.setEnabled(false);
    memoryET = (EditText) findViewById(R.id.Memory);
    memoryET.setEnabled(false);

    // status timer
    myTimer = new Timer();
    myTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            TimerMethod();
        }
    }, 0, 1000); // check interval

    // get GUI objects
    serverPortET = (EditText) findViewById(R.id.serverPort);
    serverPortET.setText(serverPort);
    dataFolderET = (EditText) findViewById(R.id.dataFolder);
    dataFolderET.setText(dataFolder);

    runBtn = (RadioButton) findViewById(R.id.RunButton);
    stopBtn = (RadioButton) findViewById(R.id.StopButton);
    quitBtn = (RadioButton) findViewById(R.id.QuitButton);

    runBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!Running) {
                try {
                    pLog("Starting up...");
                    putSettings();
                    Running = true;
                    int port = Integer.valueOf(serverPortET.getText().toString());
                    String resourceFolderPath = Environment.getExternalStorageDirectory() + "/"
                            + resourceFolder;
                    String dataFolderPath = dataFolderET.getText().toString(); // full path
                    if (!dataFolderPath.startsWith("/")) // relative to external storage dir
                        dataFolderPath = Environment.getExternalStorageDirectory() + "/" + dataFolderPath;
                    //                    CTserver.debug=true;
                    cts = new CTserver(port, resourceFolderPath, dataFolderPath); // start local webserver
                    cts.start();
                    serverPortET.setEnabled(false);
                    dataFolderET.setEnabled(false);
                    pLog("Running!");
                } catch (Exception e) {
                    pLog("CTserver Launch Error: " + e);
                    finish();
                }
            }
        }
    });

    stopBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Running) {
                pLog("Shutting down...");
                //                     stopSource();
                Running = false;
                putSettings();
                if (cts != null)
                    cts.stop(); // stop local webserver
                pLog("Stopped.");
                serverPortET.setEnabled(true);
                dataFolderET.setEnabled(true);
                System.gc(); // force a garbage collection
            }
        }
    });

    quitBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            pLog("Quitting App...");
            Running = false;
            stopBtn.setChecked(true);
            putSettings();
            finish();
        }
    });
}

From source file:com.dc.tes.License.java

private static void HeadBeat() {

    new Timer(true).schedule(new TimerTask() {

        @Override/* w  ww .j a  va  2s  . co  m*/
        public void run() {
            Message request = new Message(MessageType.LICENSE);
            request.put(MessageItem.LICENSE.SIGN, 1);
            request.put(MessageItem.LICENSE.PORT, CORE_PORT);
            request.put(MessageItem.LICENSE.SYSNAME, Sys_Name);

            System.out.println("" + request);
            String license = LicenseServerConnect(request);
            if (license.length() > 0) {
                log.error("lisence?,");
                System.exit(-1);
            }
        }

    }, 500, 60 * 1000);

}

From source file:edu.cens.loci.sensors.AccelerometerHandler.java

public void start() {

    if (mIsOn)/*from   ww  w.j a v  a  2 s.  c o m*/
        return;

    mCpuLock = cpu().newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AccelerometerHandler.CpuLock");
    mCpuLock.setReferenceCounted(false);

    mIsOn = true;

    if (mDuration > 0) {
        //mCpuLock.acquire();
        mOnTimer = new Timer("sensorTurnOnTimer");
        mOffTimer = new Timer("sensorTurnOffTimer");

        mOnTimer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                mSensorService = (SensorManager) mCxt.getSystemService(Context.SENSOR_SERVICE);

                synchronized (this) {
                    MyLog.i(LociConfig.D.ACC, TAG, "[ACC] ON ");
                    mCpuLock.acquire();
                    mSensorOn = true;
                    mSensorService.registerListener(sInstance,
                            mSensorService.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), mRate);
                }
            }
        }, 0, mPeriod);

        mOffTimer.scheduleAtFixedRate(new TimerTask() {
            public void run() {

                synchronized (this) {
                    MyLog.i(LociConfig.D.ACC, TAG, "[ACC] OFF ");
                    mSensorOn = false;
                    if (mCpuLock.isHeld())
                        mCpuLock.release();
                    mSensorService.unregisterListener(sInstance,
                            mSensorService.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));
                }
                // time to turn off sensor -- somehow send data

                //mXArr.reset();
                //mYArr.reset();
                //mZArr.reset();
                long time = Calendar.getInstance().getTime().getTime();
                float magVar = getMagnitudeVariance();
                //LociMobileManagerService.getInstance().eventAccelerometerResult(Calendar.getInstance().getTime().getTime(), magVar);

                mListener.onAccelerometerChanged(time, magVar);

                //if (LociMobileManagerService.getInstance().isMDOn()) 
                //   LociMobileManagerService.getInstance().getSystemDb().updatePowerRow(SystemLogDbAdapter.SENSOR_ACC, System.currentTimeMillis());
            }
        }, mDuration, mPeriod);

    } else {

        mCpuLock.acquire();
        mSensorService = (SensorManager) mCxt.getSystemService(Context.SENSOR_SERVICE);
        mSensorService.registerListener(this, mSensorService.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                mRate);

        mReportTimer = new Timer("SensorReportTimer");
        mReportTimer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                // send data
                long time = Calendar.getInstance().getTime().getTime();
                float magVar = getMagnitudeVariance();
                mListener.onAccelerometerChanged(time, magVar);
                //LociMobileManagerService.getInstance().eventAccelerometerResult(Calendar.getInstance().getTime().getTime(), magVar);
                //if (LociMobileManagerService.getInstance().isMDOn()) 
                //   LociMobileManagerService.getInstance().getSystemDb().updatePowerRow(SystemLogDbAdapter.SENSOR_ACC, System.currentTimeMillis());
            }
        }, 0, mDuration);
    }

    //LociMobileManagerService.getInstance().getSystemDb().addPowerRow(SystemLogDbAdapter.SENSOR_ACC, System.currentTimeMillis());
    startChkTimer();
}

From source file:com.ushahidi.android.app.UshahidiService.java

/**
 * Starts the background service//from  w  ww . j  a va  2  s.  co m
 * 
 * @return void
 */
private void startService() {

    UshahidiPref.loadSettings(mContext);
    long period = (1 * 60000);
    long delay = 500;

    mDoTask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {

                public void run() {

                    // Perform a task
                    Util.fetchReports(UshahidiService.this);
                    showNotification(UshahidiPref.totalReports);
                }

            });
        }

    };

    // Schedule the task.
    mT.scheduleAtFixedRate(mDoTask, delay, period);
}

From source file:com.hs.mail.container.simple.SimpleSpringContainer.java

private static void startPerformanceMonitor(String interval) {
    int period = Integer.parseInt(interval);
    Timer timer = new Timer();
    TimerTask memoryTask = new TimerTask() {
        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();

        @Override//from  ww  w .  ja v a2 s .  c  o  m
        public void run() {
            int threadCount = threadBean.getThreadCount();
            int peakThreadCount = threadBean.getPeakThreadCount();
            MemoryUsage heap = memoryBean.getHeapMemoryUsage();
            MemoryUsage nonHeap = memoryBean.getNonHeapMemoryUsage();
            System.out.println(sdf.format(System.currentTimeMillis()) + "\t threads=" + threadCount
                    + ";peakThreads=" + peakThreadCount + ";heap=" + heap + ";non-heap=" + nonHeap);
        }
    };
    timer.schedule(memoryTask, 0, period * 1000);
}

From source file:org.hxzon.demo.jfreechart.PolarChartDemo.java

public PolarChartDemo(String title) {
    super(title);
    PolarChartPanel chartPanel = new PolarChartPanel(polarChart1);
    //have a bug after show tooltips
    //        chartPanel.setHorizontalAxisTrace(true);
    //        chartPanel.setVerticalAxisTrace(true);
    chartPanel.setFillZoomRectangle(true);
    chartPanel.setMouseWheelEnabled(true);
    chartPanel.addMouseListener(new MyChartClickHandler(chartPanel));
    chartPanel.setPreferredSize(new Dimension(500, 270));
    getContentPane().add(chartPanel);/*  w ww  .  j a  va 2 s  .co m*/
    getContentPane().add(new ChartComboBox(chartPanel), BorderLayout.SOUTH);
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            addValue();

        }

    }, 0, 200);
}

From source file:com.makotosan.vimeodroid.ManageTransfersActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.managetransferslayout);

    registerForContextMenu(getListView());
    // Initialize timer
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override/*from www.jav a2  s  .  co m*/
        public void run() {
            handler.post(updateList);
            if (StaticInstances.transfers.isEmpty()) {
                this.cancel();
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
            }
        }
    };

    timer.scheduleAtFixedRate(task, 0, 3000);
}