All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.shinitech.djammadev.jobs.TaskScheduler Maven / Gradle / Ivy

package com.shinitech.djammadev.jobs;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Cancellable;
import com.shinitech.djammadev.time.DayDate;
import org.apache.log4j.Logger;
import scala.concurrent.duration.Duration;
import scala.concurrent.duration.FiniteDuration;

import javax.inject.Inject;
import javax.inject.Named;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created by sissoko on 31/10/2017.
 */
public class TaskScheduler implements JobScheduler {
    private static final Logger LOGGER = Logger.getLogger(TaskScheduler.class);
    private final ActorSystem system;
    private final ActorRef actor;

    @Inject
    public TaskScheduler(final ActorSystem system, @Named("task-receiver") final ActorRef actor) {
        this.system = system;
        this.actor = actor;
    }

    @Override
    public Cancellable schedule(boolean runRightNow, DayDate originOfTime, FiniteDuration interval, Job job) {
        long time = originOfTime.toDate().getTime();
        long initialDelay = 0;
        long millis = System.currentTimeMillis();
        if (!runRightNow) {
            initialDelay = time - millis;
            if (initialDelay < 0) { // Start date is in the past
                long r = (-initialDelay) % interval.toMillis(); // r < interval.toMillis()
                initialDelay = -r + interval.toMillis(); // Next run
            }
        }
        LOGGER.info("Time to next execution at " + new Date(millis + initialDelay));
        LOGGER.info("And every " + interval);
        return this.system.scheduler().schedule(
                Duration.create(initialDelay, TimeUnit.MILLISECONDS),
                interval,
                actor,
                job,
                system.dispatcher(),
                ActorRef.noSender()
        );
    }

    @Override
    public void execute(Job job) {
        this.actor.tell(job, ActorRef.noSender());
    }

    @Override
    public Cancellable scheduleOne(DayDate originOfTime, Job job) {
        long time = originOfTime.toDate().getTime();
        long millis = System.currentTimeMillis();
        long initialDelay = time - millis;
        return this.system.scheduler().scheduleOnce(
                Duration.create(initialDelay, TimeUnit.MILLISECONDS),
                actor,
                job,
                system.dispatcher(),
                ActorRef.noSender());
    }

    @Override
    public Cancellable schedule(Job job, long millis) {
        return this.system.scheduler().scheduleOnce(
                Duration.create(millis, TimeUnit.MILLISECONDS),
                actor,
                job,
                system.dispatcher(),
                ActorRef.noSender());
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy