Example usage for java.util Timer schedule

List of usage examples for java.util Timer schedule

Introduction

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

Prototype

public void schedule(TimerTask task, Date time) 

Source Link

Document

Schedules the specified task for execution at the specified time.

Usage

From source file:org.jbpm.msg.jms.AsyncProcessingTest.java

private void processAllJobs(final long maxWait) {
    boolean jobsAvailable = true;

    // install a timer that will interrupt if it takes too long
    // if that happens, it will lead to an interrupted exception and the test will fail
    TimerTask interruptTask = new TimerTask() {
        Thread testThread = Thread.currentThread();

        public void run() {
            log.debug("test " + getName() + " took too long. going to interrupt...");
            testThread.interrupt();//  w ww .  ja  va 2 s  .  c om
        }
    };
    Timer timer = new Timer();
    timer.schedule(interruptTask, maxWait);

    try {
        while (jobsAvailable) {
            log.debug("going to sleep for 200 millis, waiting for the job executor to process more jobs");
            Thread.sleep(200);
            jobsAvailable = areJobsAvailable();
        }

    } catch (InterruptedException e) {
        fail("test execution exceeded treshold of " + maxWait + " milliseconds");
    } finally {
        timer.cancel();
    }
}

From source file:edu.illinois.whereru.MainPageActivity.java

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

    intent = new Intent(this, MainTabFragmentActivity.class);
    userInfo = getSharedPreferences(PREFERENCE_NAME, 0);
    boolean firstStart = userInfo.getBoolean(PREF_APPLICATION_STATE, true);

    // If it is the first time starting this application, load up registration dialog
    if (firstStart)
        showRegistrationDialog();/*from   www. j ava2 s. c o m*/

    else {

        // Give sometime to brag about the main page.
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                // start main tab fragment activity
                startActivity(intent);
                // terminate the main page
                // without this, back button would start this activity again.
                finish();
            }

        }, 2000);

        // build friend info from DB
        FriendBuilder.build(getApplicationContext());
    }

}

From source file:dev.nhachicha.maps.MainActivity.java

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

    mSupportFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

    mMap = mSupportFrag.getMap();//from w  w w. jav a 2s  . c  o m
    if (null != mMap) {
        MAP_ZOOM_MAX = mMap.getMaxZoomLevel();
        MAP_ZOOM_MIN = mMap.getMinZoomLevel();
        mMap.setMyLocationEnabled(true);

        addMarkers();//added some dummy Markers

        //Delay the operation of finding the appropriate zoom level by giving the Maps the time to added the Marker and initialize itself 
        TimerTask task = new TimerTask() {

            public void run() {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        setProperZoomLevel(PARIS_LATLNG, 7, 1);
                    }
                });

            }
        };

        Timer timer = new Timer();
        timer.schedule(task, 1000);// schedule Map display in 1 seconds

    } else {
        Toast.makeText(this, "Sorry no map for your device :/", Toast.LENGTH_LONG).show();
    }
}

From source file:de.tor.tribes.util.ClipboardWatch.java

private synchronized void playNotification() {
    if (!Boolean.parseBoolean(GlobalOptions.getProperty("clipboard.notification"))) {
        return;//  w w w .  ja  v  a  2s  . c  om
    }

    Timer t = new Timer("ClipboardNotification", true);
    t.schedule(new TimerTask() {
        @Override
        public void run() {
            if (clip != null) {//reset clip
                clip.stop();
                clip.setMicrosecondPosition(0);
            }
            if (ac != null) {
                ac.stop();
            }

            try {
                if (org.apache.commons.lang.SystemUtils.IS_OS_WINDOWS) {
                    if (clip == null) {
                        clip = AudioSystem.getClip();
                        AudioInputStream inputStream = AudioSystem
                                .getAudioInputStream(ClockFrame.class.getResourceAsStream("/res/Ding.wav"));
                        clip.open(inputStream);
                    }
                    clip.start();
                } else {
                    if (ac == null) {
                        ac = Applet.newAudioClip(ClockFrame.class.getResource("/res/Ding.wav"));
                    }
                    ac.play();
                }
            } catch (Exception e) {
                logger.error("Failed to play notification", e);
            }
        }
    }, 0);
}

From source file:xbird.engine.sched.Scheduler.java

private final void execute(final RequestContext rc, final ScheduledEventListener listener, final long timeout) {
    if (timeout <= 0) {
        throw new IllegalArgumentException("Illegal timeout value: " + timeout);
    }//w  ww . ja  v a2s .  com
    final Request request = rc.getRequest();
    final TimerTask cancel = new TimerTask() {
        public void run() {
            try {
                listener.cancel(rc);
            } catch (RemoteException e) {
                LOG.warn("canceling task is failed: " + request.getIdentifier(), e);
            }
        }
    };
    final Timer timer = new Timer("SchedTimeout");
    timer.schedule(cancel, timeout);
    execute(rc, listener);
    timer.cancel();
}

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  w  ww. ja v  a  2 s . c  o 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:com.haoocai.jscheduler.core.tracker.ZKTaskTracker.java

private void setNextTimer(ZKTaskTracker zkTaskTracker) {
    Date nextRunTime = task.calcNextRunTime();
    LOG.info("task:{} next run time:{}.", taskID.getName(),
            DateFormatUtils.format(nextRunTime, "yyyy-MM-dd HH:mm:ss"));
    Timer timer = new Timer(taskID.getApp() + "-" + taskID.getName() + "-" + "tracker");
    task.registerNewTracker(zkTaskTracker);
    timer.schedule(zkTaskTracker, nextRunTime);
}

From source file:com.catchoom.craftarsdkexamples.SplashScreenActivity.java

private void startLaunchersActivity() {
    TimerTask task = new TimerTask() {
        public void run() {
            Intent launchersActivity = new Intent(SplashScreenActivity.this, LaunchersActivity.class);
            startActivity(launchersActivity);
            finish();//from  w  w w . ja v a  2s  .c om
        }
    };
    Timer timer = new Timer();
    timer.schedule(task, SPLASH_SCREEN_DELAY);
}

From source file:org.xwiki.extension.versioncheck.internal.EnvironmentVersionCheckTimer.java

@Override
public void initialize() throws InitializationException {
    Timer timer = new Timer();

    EnvironmentVersionCheckTask versionCheckTask = new EnvironmentVersionCheckTask();

    timer.schedule(versionCheckTask, 1000 * extensionVersionCheckConfiguration.environmentCheckInterval());
}

From source file:com.gsma.mobileconnect.utils.RestClient.java

/**
 * Execute the given request.//from w  ww. j  a  v  a  2s . c  o m
 * <p>
 * Abort the request if it exceeds the specified timeout.
 *
 * @param httpClient The client to use.
 * @param request The request to make.
 * @param context The context to use.
 * @param timeout The timeout to use.
 * @return A Http Response.
 * @throws RestException Thrown if the request fails or times out.
 */
private CloseableHttpResponse executeRequest(CloseableHttpClient httpClient, final HttpRequestBase request,
        HttpClientContext context, int timeout) throws RestException {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            request.abort();
        }
    }, timeout);

    RequestConfig localConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout)
            .setConnectTimeout(timeout).setSocketTimeout(timeout).setCookieSpec(CookieSpecs.STANDARD).build();
    request.setConfig(localConfig);
    try {
        return httpClient.execute(request, context);
    } catch (IOException ex) {
        String requestUri = request.getURI().toString();
        if (request.isAborted()) {
            throw new RestException("Rest end point did not respond", requestUri);
        }
        throw new RestException("Rest call failed", requestUri, ex);
    }
}