Example usage for java.util.concurrent ScheduledThreadPoolExecutor scheduleAtFixedRate

List of usage examples for java.util.concurrent ScheduledThreadPoolExecutor scheduleAtFixedRate

Introduction

In this page you can find the example usage for java.util.concurrent ScheduledThreadPoolExecutor scheduleAtFixedRate.

Prototype

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) 

Source Link

Document

Submits a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is, executions will commence after initialDelay , then initialDelay + period , then initialDelay + 2 * period , and so on.

Usage

From source file:Main.java

public static void main(String args[]) {
    ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(5);

    stpe.scheduleAtFixedRate(new Job1(), 0, 5, TimeUnit.SECONDS);
    stpe.scheduleAtFixedRate(new Job2(), 1, 2, TimeUnit.SECONDS);
}

From source file:Main.java

public static void main(String[] a) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(200, 300);//  ww  w  .j a  va 2 s  .  c om
    PaintSurface canvas = new PaintSurface();

    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(3);
    executor.scheduleAtFixedRate(canvas, 0L, 100L, TimeUnit.MILLISECONDS);

    f.add(canvas);
    f.setVisible(true);
}

From source file:BallRoom.java

public static void main(String[] a) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(200, 300);/*  w w  w.j a va  2  s  .co m*/
    PaintSurface canvas = new PaintSurface();

    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(3);
    executor.scheduleAtFixedRate(canvas, 0L, 100L, TimeUnit.MILLISECONDS);

    f.getContentPane().add(canvas);
    f.setVisible(true);

}

From source file:Main.java

public static void main(String[] args) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(2);
    scheduledThreadPoolExecutor.scheduleAtFixedRate(() -> {

        throw new RuntimeException(" scheduleAtFixedRate test ScheduledThreadPoolExecutor");
    }, 0, 3000, TimeUnit.MILLISECONDS);

    scheduledThreadPoolExecutor.scheduleAtFixedRate(() -> {

        System.out.println("scheduleAtFixedRate: " + LocalDateTime.now().format(formatter));
    }, 0, 2000, TimeUnit.MILLISECONDS);

    scheduledThreadPoolExecutor.schedule(() -> {

        System.out.println("schedule");
    }, 1, TimeUnit.SECONDS);//from w  w w  .  j av a 2s  .c o  m
}

From source file:com.l2jfree.util.concurrent.L2ThreadPool.java

public static ScheduledFuture<?> scheduleAtFixedRate(Runnable r, long delay, long period) {
    r = ExecuteWrapper.wrap(r);/*w  ww.j  a  va 2s .c o  m*/
    delay = validate(delay);
    period = validate(period);

    final ScheduledThreadPoolExecutor stpe = getRandomPool(_scheduledPools);
    final ScheduledFuture<?> sf = stpe.scheduleAtFixedRate(r, delay, period, TimeUnit.MILLISECONDS);

    return new ScheduledFutureWrapper(sf);
}

From source file:edu.berkeley.sparrow.examples.SimpleFrontend.java

public void run(String[] args) {
    try {/*w  w w.  j  ava 2 s .  c om*/
        OptionParser parser = new OptionParser();
        parser.accepts("c", "configuration file").withRequiredArg().ofType(String.class);
        parser.accepts("help", "print help statement");
        OptionSet options = parser.parse(args);

        if (options.has("help")) {
            parser.printHelpOn(System.out);
            System.exit(-1);
        }

        // Logger configuration: log to the console
        BasicConfigurator.configure();
        LOG.setLevel(Level.DEBUG);

        Configuration conf = new PropertiesConfiguration();

        if (options.has("c")) {
            String configFile = (String) options.valueOf("c");
            conf = new PropertiesConfiguration(configFile);
        }

        int arrivalPeriodMillis = conf.getInt(JOB_ARRIVAL_PERIOD_MILLIS, DEFAULT_JOB_ARRIVAL_PERIOD_MILLIS);
        int experimentDurationS = conf.getInt(EXPERIMENT_S, DEFAULT_EXPERIMENT_S);
        LOG.debug("Using arrival period of " + arrivalPeriodMillis + " milliseconds and running experiment for "
                + experimentDurationS + " seconds.");
        int tasksPerJob = conf.getInt(TASKS_PER_JOB, DEFAULT_TASKS_PER_JOB);
        int taskDurationMillis = conf.getInt(TASK_DURATION_MILLIS, DEFAULT_TASK_DURATION_MILLIS);

        int schedulerPort = conf.getInt(SCHEDULER_PORT, SchedulerThrift.DEFAULT_SCHEDULER_THRIFT_PORT);
        String schedulerHost = conf.getString(SCHEDULER_HOST, DEFAULT_SCHEDULER_HOST);
        client = new SparrowFrontendClient();
        client.initialize(new InetSocketAddress(schedulerHost, schedulerPort), APPLICATION_ID, this);

        JobLaunchRunnable runnable = new JobLaunchRunnable(tasksPerJob, taskDurationMillis);
        ScheduledThreadPoolExecutor taskLauncher = new ScheduledThreadPoolExecutor(1);
        taskLauncher.scheduleAtFixedRate(runnable, 0, arrivalPeriodMillis, TimeUnit.MILLISECONDS);

        long startTime = System.currentTimeMillis();
        LOG.debug("sleeping");
        while (System.currentTimeMillis() < startTime + experimentDurationS * 1000) {
            Thread.sleep(100);
        }
        taskLauncher.shutdown();
    } catch (Exception e) {
        LOG.error("Fatal exception", e);
    }
}

From source file:com.n0n3m4.q3e.Q3ECallbackObj.java

public void init(int size) {
    if (mAudioTrack != null)
        return;/*from w  w  w.  java  2s  .  com*/
    if ((Q3EUtils.q3ei.isQ3) || (Q3EUtils.q3ei.isRTCW) || (Q3EUtils.q3ei.isQ1) || (Q3EUtils.q3ei.isQ2))
        size /= 8;

    mAudioData = new byte[size];
    int sampleFreq = 44100;

    /*                        _.---"'"""""'`--.._
                     _,.-'                   `-._
                 _,."                            -.
             .-""   ___...---------.._             `.
             `---'""                  `-.            `.
                                         `.            \
                                           `.           \
                                             \           \
                                              .           \
                                              |            .
                                              |            |
                        _________             |            |
                  _,.-'"         `"'-.._      :            |
              _,-'                      `-._.'             |
           _.'            OUYA               `.             '
      _.-.    _,+......__                           `.          .
    .'    `-"'           `"-.,-""--._                 \        /
    /    ,'                  |    __  \                 \      /
    `   ..                       +"  )  \                 \    /
    `.'  \          ,-"`-..    |       |                  \  /
    / " |        .'       \   '.    _.'                   .'
    |,.."--"""--..|    "    |    `""`.                     |
    ,"               `-._     |        |                     |
    .'                     `-._+         |                     |
    /                           `.                        /     |
    |    `     '                  |                      /      |
    `-.....--.__                  |              |      /       |
    `./ "| / `-.........--.-   '              |    ,'        '
    /| ||        `.'  ,'   .'               |_,-+         /
    / ' '.`.        _,'   ,'     `.          |   '   _,.. /
    /   `.  `"'"'""'"   _,^--------"`.        |    `.'_  _/
    /... _.`:.________,.'              `._,.-..|        "'
    `.__.'                                 `._  /
                                   "' */

    int bufferSize = Math.max((Q3EUtils.isOuya) ? 0 : 3 * size, AudioTrack.getMinBufferSize(sampleFreq,
            AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT));
    mAudioTrack = new Q3EAudioTrack(AudioManager.STREAM_MUSIC, sampleFreq,
            AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT, bufferSize,
            AudioTrack.MODE_STREAM);
    mAudioTrack.play();
    long sleeptime = (size * 1000000000l) / (2 * 2 * sampleFreq);
    ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(5);
    stpe.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            if (reqThreadrunning) {
                Q3EJNI.requestAudioData();
            }
        }
    }, 0, sleeptime, TimeUnit.NANOSECONDS);
}

From source file:net.roboconf.iaas.openstack.IaasOpenstack.java

@Override
public String createVM(String machineImageId, String ipMessagingServer, String channelName,
        String applicationName) throws IaasException, CommunicationToIaasException {

    if (machineImageId == null || "".equals(machineImageId))
        machineImageId = this.machineImageId;

    // Normally we use flavor names in the configuration, not IDs
    // But lets's assume it can be an ID...
    String flavorId = this.flavor;
    Flavors flavors = this.novaClient.flavors().list(true).execute();
    for (Flavor f : flavors) {
        if (f.getName().equals(this.flavor))
            flavorId = f.getId();//from   w w w . j a  va  2s.com
    }

    ServerForCreate serverForCreate = new ServerForCreate();
    serverForCreate.setName(applicationName + "." + channelName);
    serverForCreate.setFlavorRef(flavorId);
    serverForCreate.setImageRef(machineImageId);
    if (this.keypair != null)
        serverForCreate.setKeyName(this.keypair);
    serverForCreate.getSecurityGroups().add(new ServerForCreate.SecurityGroup(this.securityGroup));

    // User data will be retrieved (like on Amazon WS) on guest OS as
    // http://169.254.169.254/latest/user-data
    String userData = "applicationName=" + applicationName + "\nmachineName=" + channelName //TBD machineName=channelName
            + "\nchannelName=" + channelName + "\nipMessagingServer=" + ipMessagingServer;
    serverForCreate.setUserData(new String(Base64.encodeBase64(userData.getBytes())));

    final Server server = this.novaClient.servers().boot(serverForCreate).execute();
    System.out.println(server);

    // Wait for server to be in ACTIVE state, before associating floating IP
    try {
        final ScheduledThreadPoolExecutor timer = new ScheduledThreadPoolExecutor(1);
        timer.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
                Server checked = IaasOpenstack.this.novaClient.servers().show(server.getId()).execute();
                if ("ACTIVE".equals(checked.getStatus())) {
                    timer.shutdown();
                }
            }
        }, 10, 5, TimeUnit.SECONDS);
        timer.awaitTermination(120, TimeUnit.SECONDS);
    } catch (Exception ignore) {
        /*ignore*/ }

    // Associate floating IP
    if (this.floatingIpPool != null) {
        FloatingIps ips = this.novaClient.floatingIps().list().execute();

        FloatingIp ip = null;
        for (FloatingIp ip2 : ips) {
            System.out.println("ip=" + ip2);
            ip = ip2;
        }
        //FloatingIp ip = ips.allocate(this.floatingIpPool).execute();
        if (ip != null) {
            this.novaClient.servers().associateFloatingIp(server.getId(), ip.getIp()).execute();
        }
    }

    return server.getId();
}

From source file:com.example.dwr.ticketcenter.CallCenter.java

/**
 * Create a new publish thread and start it
 *///from www.jav  a2 s . c om
public CallCenter() {
    // Start with some calls waiting
    addRandomKnownCall();
    addRandomUnknownCall();
    addRandomUnknownCall();
    addRandomUnknownCall();

    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, new DaemonThreadFactory());
    //noinspection ThisEscapedInObjectConstruction
    executor.scheduleAtFixedRate(this, 2, 2, TimeUnit.SECONDS);
}