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:com.SmartDial.ForegroundService.java

/**
 * Put the service in a foreground state to prevent app from being killed
 * by the OS./*  w  w  w .  ja va 2 s.  c  om*/
 */
public void keepAwake() {
    final Handler handler = new Handler();

    if (!this.inSilentMode()) {
        startForeground(NOTIFICATION_ID, makeNotification());
    } else {
        Log.w("BackgroundMode", "In silent mode app may be paused by OS!");
    }

    BackgroundMode.deleteUpdateSettings();

    keepAliveTask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    // Nothing to do here
                    // Log.d("BackgroundMode", "" + new Date().getTime());
                }
            });
        }
    };

    scheduler.schedule(keepAliveTask, 0, 1000);
}

From source file:cl.tide.fm.sensonet.SensonetClient.java

public void start(List<SensorView> s) {
    long interval = SettingsController.getInterval();
    interval = interval < 10000 ? 10000 : interval;
    System.err.println("interval update " + interval);

    stop = false;/*from www  . jav  a  2s.c  om*/
    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            if (!isLogged)
                login(SettingsController.getSensonetUser(), SettingsController.getSensonetPassword());
            System.out.println("\n Sensonet Status " + isOnline + " " + !stop + " " + isLogged);
            if (isOnline && !stop) {
                if (myDatasource == null) {
                    findOrCreateDataSource("Senso");
                    if (variables.isEmpty())
                        findOrCreateVariables(s);
                }
                if (variables.size() > 0) {
                    variables.forEach((va) -> {
                        try {
                            BasicNameValuePair param = new BasicNameValuePair("value",
                                    va.sensor.getValue() + "");
                            List<NameValuePair> params = new ArrayList<>();
                            params.add(param);
                            HttpPost post = new HttpPost(
                                    baseUrl + "project/datasource/variable/value/" + va.id);

                            post.setEntity(new UrlEncodedFormEntity(params));
                            CloseableHttpResponse result = client.execute(post);
                            int statusCode = result.getStatusLine().getStatusCode();
                            if (statusCode == 200) {
                                System.out.println(va.name + " enviado correctamente ");
                            } else {
                                System.err.println(statusCode + " Ocurrio un error al enviar " + va.name);
                            }
                            result.close();

                        } catch (IOException ex) {
                            Logger.getLogger(SensonetClient.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    });
                } else {
                    //almacenar los datos  y envialos luego?
                    System.err.println("No hay variables");
                    findOrCreateVariables(s);
                }
            } else {
                System.err.println("sensonet is offline");
            }
        }
    }, 0, interval);
}

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   ww  w  .j a v  a2s .  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:com.sidekickApp.PusherClass.java

private void startDecayTimer() {
    log("startDecayTimer()");
    decayTimer = new Timer("decayTimer", true);
    long initialDelay = 0;
    long interval = 250;

    decayTimer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            // calculate decay
            interest = interest * decayFactor;
            if (interest > 100) {
                interest = 100;/* w ww  .  ja v  a 2 s. c  o  m*/
            }
            if (interest < 0.1) {
                interest = 0;
            }
            log("Pusher: interest = " + interest);

            Intent i = new Intent();
            int interestI = (int) interest;
            i.putExtra("com.sidekickApp.interest", interestI);
            i.setAction(AppState.SIDECAR_INTEREST);
            main.sendBroadcast(i);
        }
    }, initialDelay, interval);

}

From source file:com.microsoft.speech.tts.Authentication.java

public Authentication(String apiKey) {
    this.apiKey = apiKey;

    Thread th = new Thread(new Runnable() {
        @Override// w  w  w  .ja va 2  s. co  m
        public void run() {
            RenewAccessToken();
        }
    });

    try {
        th.start();
        th.join();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // renew the accessToken every specified minutes
    accessTokenRenewer = new Timer();
    nineMinitesTask = new TimerTask() {
        public void run() {
            RenewAccessToken();
        }
    };

    accessTokenRenewer.schedule(nineMinitesTask, RefreshTokenDuration, RefreshTokenDuration);
}

From source file:deincraftlauncher.start.StartMinecraft.java

public static void startMC(Modpack pack) {

    try {/*from  ww  w.ja  v  a  2 s  . c  om*/

        System.out.println("trying to start minecraft");

        GameInfos infos = new GameInfos(pack.getName(), new File(pack.getPath()),
                new GameVersion(pack.getMCVersion(), pack.getGameType()), new GameTweak[] { GameTweak.FORGE });
        System.out.println("GameInfos done");

        System.out.println("Zugangsdaten: " + settings.getUsername() + settings.getPassword());

        Authenticator authenticator = new Authenticator(Authenticator.MOJANG_AUTH_URL,
                AuthPoints.NORMAL_AUTH_POINTS);
        AuthResponse rep = authenticator.authenticate(AuthAgent.MINECRAFT, settings.getUsername(),
                settings.getPassword(), "");
        AuthInfos authInfos = new AuthInfos(rep.getSelectedProfile().getName(), rep.getAccessToken(),
                rep.getSelectedProfile().getId());
        System.out.println("authinfos done");

        //AuthInfos authInfos = new AuthInfos(settings.getUsername(), MCAuthentication.getToken(settings.getUsername(), settings.getPassword()), MCAuthentication.getUUID(settings.getUsername(), settings.getPassword()));

        ExternalLaunchProfile profile = MinecraftLauncher.createExternalProfile(infos, getFolder(pack),
                authInfos);
        List<String> vmArgs = profile.getVmArgs();
        vmArgs.add(String.valueOf("-Xms" + settings.getRAM() + "m"));
        //System.out.println("vm args: " + vmArgs);
        profile.setVmArgs(vmArgs);
        ExternalLauncher launcher = new MCLauncher(profile);
        System.out.println("profile and launcher done " + launcher.getProfile());

        Process launch = launcher.launch();

        BufferedReader stdout = new BufferedReader(new InputStreamReader(launch.getInputStream()));
        String line;

        while ((line = stdout.readLine()) != null) {
            System.out.println(line);
        }
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Platform.runLater(() -> {
                    System.out.println("minecraft started, changing start state");
                    pack.setStartState(PackViewHandler.StartState.Loading);
                    pack.setStartText("gestartet");
                });
            }
        }, 8000);

        checkAlive(launch, pack);

    } catch (LaunchException | AuthenticationException | IOException ex) {
        Logger.getLogger(StartMinecraft.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:monitoring.tools.ITunesApple.java

private void resetStream() throws Exception {

    kafka.initProxy(this.params.getKafkaEndpoint());
    //kafka.initProducer(this.params.getKafkaEndpoint());

    this.reported = new ArrayList<>();
    firstConnection = true;/*from   www. j  ava  2  s  .c om*/
    firstApiCall();

    timer = new Timer();
    timer.schedule(new TimerTask() {
        public void run() {
            if (firstConnection) {
                logger.debug("Connection established");
                firstConnection = false;
                System.out.println("First connection stablished");
            } else {
                try {
                    apiCall();
                } catch (IOException e) {
                    logger.error("There was an unexpected error with the API call");
                }
            }
        }

    }, 0, Integer.parseInt(params.getTimeSlot()) * 1000);
}

From source file:com.app.sniffy.MainActivity.java

@Override
public void onStart() {
    super.onStart();

    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    if (settings.getString("key", null) != null) {
        if (!isMyServiceRunning()) {
            // intent to start service
            Intent mServiceIntent = new Intent(this, SentBoxService.class);
            startService(mServiceIntent);
        }//from   w w w  .j  a  va 2  s  .  c om
    }

    if (storedKey != null) {
        timer = new Timer();
        timer.schedule(new TimerTask() {

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

                    public void run() {

                        String currentTime = df.format(new Date());
                        String[] time = currentTime.split(",");

                        TextView digi_time = (TextView) findViewById(R.id.digi_time);
                        digi_time.setText(time[0]);

                        TextView digi_time_meredian = (TextView) findViewById(R.id.digi_time_meredian);
                        digi_time_meredian.setText(time[1]);

                        TextView digi_time_day = (TextView) findViewById(R.id.digi_time_day);
                        digi_time_day.setText(time[2] + ",");

                        TextView digi_time_date = (TextView) findViewById(R.id.digi_time_date);
                        digi_time_date.setText(time[3]);
                    }
                });

            }

        }, 0, 1000);
    }

}

From source file:com.connectsdk.discovery.provider.CastDiscoveryProvider.java

@Override
public void start() {
    stop();/*from  w ww  .  j a  v a 2  s  .co  m*/

    addCallbackTimer = new Timer();
    addCallbackTimer.schedule(new TimerTask() {

        @Override
        public void run() {
            sendSearch();
        }
    }, 100, RESCAN_INTERVAL);

    removeCallbackTimer = new Timer();
    removeCallbackTimer.schedule(new TimerTask() {

        @Override
        public void run() {
            new Handler(Looper.getMainLooper()).post(new Runnable() {

                @Override
                public void run() {
                    mMediaRouter.removeCallback(mMediaRouterCallback);
                }
            });
        }
    }, 9100, RESCAN_INTERVAL);
}

From source file:ExampleMIDlet.java

private void startTimer() {

    // Create a task to be run
    task = new TimerTask() {
        private boolean isPaused;
        private int count;

        public void run() {
            // Pause or resume the MIDlet.
            System.out.println("Timer scheduled");
            if (count++ == 4) {
                // Terminate the MIDlet
                try {
                    ExampleMIDlet.this.destroyApp(true);
                } catch (MIDletStateChangeException ex) {
                    // Ignore pleas for mercy!
                }//from w  w  w .  ja  v  a2 s .  co  m
                ExampleMIDlet.this.notifyDestroyed();
                return;
            }
            if (isPaused) {
                System.out.println(">> Resuming MIDlet");
                ExampleMIDlet.this.resumeRequest();
                isPaused = false;
            } else {
                System.out.println(">> Pausing MIDlet");
                isPaused = true;
                ExampleMIDlet.this.pauseApp();
                ExampleMIDlet.this.notifyPaused();
            }
        }
    };

    // Create a timer and schedule it to run
    timer = new Timer();
    timer.schedule(task, timerInterval, timerInterval);
    System.out.println("Timer started.");
}