Java Code Examples for java.util.TimerTask#run()

The following examples show how to use java.util.TimerTask#run() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cfg4j   File: PeriodicalReloadStrategy.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void register(final Reloadable resource) {
  LOG.debug("Registering resource " + resource
      + " with reload time of " + duration + " " + timeUnit.toString().toLowerCase());

  TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
      try {
        resource.reload();
      } catch (Exception e) {
        LOG.warn("Periodical resource reload failed. Will re-try at the next scheduled time.", e);
      }
    }
  };

  timerTask.run();

  tasks.put(resource, timerTask);
  timer.schedule(timerTask, timeUnit.toMillis(duration), timeUnit.toMillis(duration));
}
 
Example 2
Source Project: flink   File: LocalInputChannelTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests that {@link LocalInputChannel#retriggerSubpartitionRequest(Timer, int)} would throw
 * {@link PartitionNotFoundException} which is set onto the input channel then.
 */
@Test
public void testChannelErrorWhileRetriggeringRequest() {
	final SingleInputGate inputGate = createSingleInputGate(1);
	final LocalInputChannel localChannel = createLocalInputChannel(inputGate, new ResultPartitionManager());

	final Timer timer = new Timer(true) {
		@Override
		public void schedule(TimerTask task, long delay) {
			task.run();

			try {
				localChannel.checkError();

				fail("Should throw a PartitionNotFoundException.");
			} catch (PartitionNotFoundException notFound) {
				assertThat(localChannel.partitionId, Matchers.is(notFound.getPartitionId()));
			} catch (IOException ex) {
				fail("Should throw a PartitionNotFoundException.");
			}
		}
	};

	try {
		localChannel.retriggerSubpartitionRequest(timer, 0);
	} finally {
		timer.cancel();
	}
}
 
Example 3
Source Project: ClockView   File: TimeCountDownView.java    License: Apache License 2.0 5 votes vote down vote up
public void startCountDown(){
    timer= new Timer();
    TimerTask timerTask =new TimerTask() {
        @Override
        public void run() {
            handler.sendEmptyMessage(0);
        }
    };
    timer.schedule(timerTask,0,1000);
    timerTask.run();
}
 
Example 4
Source Project: flink   File: LocalInputChannelTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests that {@link LocalInputChannel#retriggerSubpartitionRequest(Timer, int)} would throw
 * {@link PartitionNotFoundException} which is set onto the input channel then.
 */
@Test
public void testChannelErrorWhileRetriggeringRequest() {
	final SingleInputGate inputGate = createSingleInputGate(1);
	final LocalInputChannel localChannel = createLocalInputChannel(inputGate, new ResultPartitionManager());

	final Timer timer = new Timer(true) {
		@Override
		public void schedule(TimerTask task, long delay) {
			task.run();

			try {
				localChannel.checkError();

				fail("Should throw a PartitionNotFoundException.");
			} catch (PartitionNotFoundException notFound) {
				assertThat(localChannel.partitionId, Matchers.is(notFound.getPartitionId()));
			} catch (IOException ex) {
				fail("Should throw a PartitionNotFoundException.");
			}
		}
	};

	try {
		localChannel.retriggerSubpartitionRequest(timer, 0);
	} finally {
		timer.cancel();
	}
}
 
Example 5
@Override
public TimerTask decorate(TimerTask timerTask) {
    return new TimerTask() {
        @Override
        public void run() {
            SecurityContext previousSecurityContext = SecurityContextHolder.getContext();
            try {
                SecurityContextHolder.setContext(securityContext);
                timerTask.run();
            } finally {
                SecurityContextHolder.setContext(previousSecurityContext);
            }
        }
    };
}
 
Example 6
@Test
public void testNodeHealthScript() throws Exception {
  String errorScript = "echo ERROR\n echo \"Tracker not healthy\"";
  String normalScript = "echo \"I am all fine\"";
  String timeOutScript =
    Shell.WINDOWS ? "@echo off\nping -n 4 127.0.0.1 >nul\necho \"I am fine\""
    : "sleep 4\necho \"I am fine\"";
  Configuration conf = new Configuration();
  writeNodeHealthScriptFile(normalScript, true);
  NodeHealthScriptRunner nodeHealthScriptRunner = new NodeHealthScriptRunner(
          nodeHealthscriptFile.getAbsolutePath(),
          500, 1000, new String[] {});
  nodeHealthScriptRunner.init(conf);
  TimerTask timerTask = nodeHealthScriptRunner.getTimerTask();

  timerTask.run();
  // Normal Script runs successfully
  Assert.assertTrue("Node health status reported unhealthy",
      nodeHealthScriptRunner.isHealthy());
  Assert.assertEquals("", nodeHealthScriptRunner.getHealthReport());

  // Error script.
  writeNodeHealthScriptFile(errorScript, true);
  // Run timer
  timerTask.run();
  Assert.assertFalse("Node health status reported healthy",
      nodeHealthScriptRunner.isHealthy());
  Assert.assertTrue(
      nodeHealthScriptRunner.getHealthReport().contains("ERROR"));
  
  // Healthy script.
  writeNodeHealthScriptFile(normalScript, true);
  timerTask.run();
  Assert.assertTrue("Node health status reported unhealthy",
      nodeHealthScriptRunner.isHealthy());
  Assert.assertEquals("", nodeHealthScriptRunner.getHealthReport());

  // Timeout script.
  writeNodeHealthScriptFile(timeOutScript, true);
  timerTask.run();
  Assert.assertFalse("Node health status reported healthy even after timeout",
  nodeHealthScriptRunner.isHealthy());
  Assert.assertEquals(
          NodeHealthScriptRunner.NODE_HEALTH_SCRIPT_TIMED_OUT_MSG,
          nodeHealthScriptRunner.getHealthReport());
}
 
Example 7
Source Project: big-c   File: TestNodeHealthService.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testNodeHealthScript() throws Exception {
  RecordFactory factory = RecordFactoryProvider.getRecordFactory(null);
  NodeHealthStatus healthStatus =
      factory.newRecordInstance(NodeHealthStatus.class);
  String errorScript = "echo ERROR\n echo \"Tracker not healthy\"";
  String normalScript = "echo \"I am all fine\"";
  String timeOutScript = Shell.WINDOWS ? "@echo off\nping -n 4 127.0.0.1 >nul\necho \"I am fine\""
      : "sleep 4\necho \"I am fine\"";
  Configuration conf = getConfForNodeHealthScript();
  conf.writeXml(new FileOutputStream(nodeHealthConfigFile));
  conf.addResource(nodeHealthConfigFile.getName());

  writeNodeHealthScriptFile(normalScript, true);
  NodeHealthCheckerService nodeHealthChecker = new NodeHealthCheckerService();
  nodeHealthChecker.init(conf);
  NodeHealthScriptRunner nodeHealthScriptRunner =
      nodeHealthChecker.getNodeHealthScriptRunner();
  TimerTask timerTask = nodeHealthScriptRunner.getTimerTask();

  timerTask.run();

  setHealthStatus(healthStatus, nodeHealthChecker.isHealthy(),
      nodeHealthChecker.getHealthReport(),
      nodeHealthChecker.getLastHealthReportTime());
  LOG.info("Checking initial healthy condition");
  // Check proper report conditions.
  Assert.assertTrue("Node health status reported unhealthy", healthStatus
      .getIsNodeHealthy());
  Assert.assertTrue("Node health status reported unhealthy", healthStatus
      .getHealthReport().equals(nodeHealthChecker.getHealthReport()));

  // write out error file.
  // Healthy to unhealthy transition
  writeNodeHealthScriptFile(errorScript, true);
  // Run timer
  timerTask.run();
  // update health status
  setHealthStatus(healthStatus, nodeHealthChecker.isHealthy(),
      nodeHealthChecker.getHealthReport(),
      nodeHealthChecker.getLastHealthReportTime());
  LOG.info("Checking Healthy--->Unhealthy");
  Assert.assertFalse("Node health status reported healthy", healthStatus
      .getIsNodeHealthy());
  Assert.assertTrue("Node health status reported healthy", healthStatus
      .getHealthReport().equals(nodeHealthChecker.getHealthReport()));
  
  // Check unhealthy to healthy transitions.
  writeNodeHealthScriptFile(normalScript, true);
  timerTask.run();
  setHealthStatus(healthStatus, nodeHealthChecker.isHealthy(),
      nodeHealthChecker.getHealthReport(),
      nodeHealthChecker.getLastHealthReportTime());
  LOG.info("Checking UnHealthy--->healthy");
  // Check proper report conditions.
  Assert.assertTrue("Node health status reported unhealthy", healthStatus
      .getIsNodeHealthy());
  Assert.assertTrue("Node health status reported unhealthy", healthStatus
      .getHealthReport().equals(nodeHealthChecker.getHealthReport()));

  // Healthy to timeout transition.
  writeNodeHealthScriptFile(timeOutScript, true);
  timerTask.run();
  setHealthStatus(healthStatus, nodeHealthChecker.isHealthy(),
      nodeHealthChecker.getHealthReport(),
      nodeHealthChecker.getLastHealthReportTime());
  LOG.info("Checking Healthy--->timeout");
  Assert.assertFalse("Node health status reported healthy even after timeout",
      healthStatus.getIsNodeHealthy());
  Assert.assertTrue("Node script time out message not propogated",
      healthStatus.getHealthReport().equals(
          NodeHealthScriptRunner.NODE_HEALTH_SCRIPT_TIMED_OUT_MSG
          + NodeHealthCheckerService.SEPARATOR
          + nodeHealthChecker.getDiskHandler().getDisksHealthReport(false)));
}
 
Example 8
Source Project: bean-sdk-android   File: SendBuffer.java    License: MIT License 4 votes vote down vote up
/**
 * Schedules the send task to run either immediately or at SEND_INTERVAL.
 *
 * @param runNow true runs the task immediately, false schedules it for SEND_INTERVAL ms from
 *               now
 */
private void scheduleSendTask(boolean runNow) {
    TimerTask task = new TimerTask() {
        @Override
        public void run() {

            byte[] packet;

            try {
                packet = packets.get(0);

            } catch (IndexOutOfBoundsException e) {
                // No packets left; return without scheduling another run
                return;

            }

            charc.setValue(packet);
            boolean result = gattClient.writeCharacteristic(charc);

            if (result) {
                packets.remove(0);
                int id = ids.remove(0);
                retries = 0;

                if (onPacketSent != null) {
                    onPacketSent.onResult(id);
                }
                Log.d(TAG, "Packet " + id + " sent after " + retries + " retries");

            } else {
                retries++;

            }

            scheduleSendTask(false);
        }
    };

    if (runNow) {
        task.run();

    } else {
        sendTimer.schedule(task, SEND_INTERVAL);

    }
}
 
Example 9
Source Project: RDFS   File: TestNodeHealthService.java    License: Apache License 2.0 4 votes vote down vote up
public void testNodeHealthScript() throws Exception {
  TaskTrackerHealthStatus healthStatus = new TaskTrackerHealthStatus();
  String errorScript = "echo ERROR\n echo \"Tracker not healthy\"";
  String normalScript = "echo \"I am all fine\"";
  String timeOutScript = "sleep 4\n echo\"I am fine\"";
  Configuration conf = getConfForNodeHealthScript();
  conf.writeXml(new FileOutputStream(nodeHealthConfigFile));

  NodeHealthCheckerService nodeHealthChecker = new NodeHealthCheckerService(
      conf);
  TimerTask timer = nodeHealthChecker.getTimer();
  writeNodeHealthScriptFile(normalScript, true);
  timer.run();

  nodeHealthChecker.setHealthStatus(healthStatus);
  LOG.info("Checking initial healthy condition");
  // Check proper report conditions.
  assertTrue("Node health status reported unhealthy", healthStatus
      .isNodeHealthy());
  assertTrue("Node health status reported unhealthy", healthStatus
      .getHealthReport().isEmpty());

  // write out error file.
  // Healthy to unhealthy transition
  writeNodeHealthScriptFile(errorScript, true);
  // Run timer
  timer.run();
  // update health status
  nodeHealthChecker.setHealthStatus(healthStatus);
  LOG.info("Checking Healthy--->Unhealthy");
  assertFalse("Node health status reported healthy", healthStatus
      .isNodeHealthy());
  assertFalse("Node health status reported healthy", healthStatus
      .getHealthReport().isEmpty());
  
  // Check unhealthy to healthy transitions.
  writeNodeHealthScriptFile(normalScript, true);
  timer.run();
  nodeHealthChecker.setHealthStatus(healthStatus);
  LOG.info("Checking UnHealthy--->healthy");
  // Check proper report conditions.
  assertTrue("Node health status reported unhealthy", healthStatus
      .isNodeHealthy());
  assertTrue("Node health status reported unhealthy", healthStatus
      .getHealthReport().isEmpty());

  // Healthy to timeout transition.
  writeNodeHealthScriptFile(timeOutScript, true);
  timer.run();
  nodeHealthChecker.setHealthStatus(healthStatus);
  LOG.info("Checking Healthy--->timeout");
  assertFalse("Node health status reported healthy even after timeout",
      healthStatus.isNodeHealthy());
  assertEquals("Node time out message not propogated", healthStatus
      .getHealthReport(),
      NodeHealthCheckerService.NODE_HEALTH_SCRIPT_TIMED_OUT_MSG);
}