Routine in Java within loop of repetition

0

I have a method in Java that sends an email with a doc attachment, and is working correctly. However, this method takes around 50 seconds to execute the entire shipping process. But now I need to run it several times in sequence. How can I make this method run, but does it only start again when it finishes?

Example:

while(diretorio!=""){

  enviaEmail(destinatario,assunto,anexo) // isso leva 50segundos executando, mas eu quero que só execute novamente após o término de cada envio..

  }
//o que está acontecendo é que ele está enviando um em cima do outro, sem aguardar cada envio ser concluido

OBS. if the solution is with Threads, where do I put Thread?

    
asked by anonymous 07.11.2016 / 01:38

2 answers

3

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.

    
07.11.2016 / 04:02
-1

First of all it would be interesting to make sure that your approach is in fact the best for this situation, do you have to send the same email 50 times? It is not easier (and less expensive) to send a single email to 50 different addresses through hidden copy, so each address would receive as if it were the only one? If you decide to do this through Threads (and send 50 emails ...) then a new Thread is created within the loop, where you are calling the method of sending emails.

    
07.11.2016 / 02:01