Depending on your needs, I see at least two possibilities.
Timer
If you want to execute a process again and again, but without interleaving the executions, that is, always leaving a gap between them, you can use Timer
to schedule such execution.
There are several issues related here in SOpt that can help you:
Queue
If all you want is to queue submissions so that they do not all run at the same time, you can create a queue to put data of the messages to be sent.
Then create a thread to consume the items in the queue, sending the emails one by one, or batch by lot as you prefer. Exact implementation depends on the outcome you want.
In terms of class, it would be interesting to look at how to implement a queue (eg : LinkedList
) or a deque (eg: ArrayDeque
).
If you use different threads to access the file, you need a concurrent implementation, such as LinkedBlockingQueue
.
In this case, the thread can be created anywhere, as long as it has access to the queue. Example implementation:
public class GerenciadorEnvio implements Runnable {
private BlockingQueue<Mensagem> queue = new LinkedBlockingQueue<>();
public void enviarMensagem(Mensagem m) {
//coloca uma mensagem na fila
queue.add(m);
}
@Override
public void run() {
//laço infinito - uma condição de parada pode ser adicionada
for (;;) {
try {
//Retira um item da fila, se não houver, a thread fica bloqueada aguardando
Mensagem item = queue.take();
//enviar e-mail(s)
} catch (Exception e) {
//logar erro
}
}
}
}
The Mensagem
class here is just an example that should contain all the information needed to send an email or a group of emails.
Example usage:
GerenciadorEnvio ge = new GerenciadorEnvio();
new Thread(ge).start();
ge.postarMensagem(new Mensagem(...));
In this case, you can send as many messages as you want. If there are no messages, the thread method in run
will wait, blocked by take
method.
When a new message is added to the queue, the thread will be unlocked and execute the excerpt that sends the email.
After the process is finished, the loop returns at the beginning and checks to see if there are more messages to send. If not, the thread is waiting, if it does, it picks up the next message and processes it.