How do I run my code asynchronously and in real time or with each given time span?

Asked

Viewed 54 times

-3

I need to know how to run this code on my server, asynchronously and in real time, or every 5 minutes, for example.

                    String asB64 = Base64.getEncoder().encodeToString("XXXX:YYYYYYYYY".getBytes("utf-8"));
                    URL url = new URL("https://us.saas.orbiwise.com/rest/nodes/XXXXXXXXX/payloads/ul/latest");//your url i.e fetch data from .
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                    conn.setRequestMethod("GET");
                    conn.setRequestProperty("Authorization", "Basic " + asB64);
                    conn.setRequestProperty("Accept", "application/json");
                    conn.setRequestProperty("Access-Control-Allow-Origin", "*");

                    if (conn.getResponseCode() != 200) {
                        throw new RuntimeException("Failed : HTTP Error code : "
                                + conn.getResponseCode());
                    }
                    InputStreamReader in = new InputStreamReader(conn.getInputStream());
                    BufferedReader br = new BufferedReader(in);
                    String output;
                    String result = "";
                    output = br.readLine();
                    Objeto obj = new Objeto();

                    JSONObject jsonObject = new JSONObject(output);

                    if (jsonObject.has("id")) {
                        obj.setid(jsonObject.getLong("id"));
                        // System.out.println("id ok");
                    }
                    if (jsonObject.has("timestamp")) {
                        String timestamp = jsonObject.getString("timestamp");
                        timestamp = timestamp.replace("Z", "").replace("T", " ");
                        DateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
                        DateFormat writeFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

                        Date date = null;
                        try {
                            date = readFormat.parse(timestamp);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        if (date != null) {
                            timestamp = writeFormat.format(date);
                            obj.setTimestamp(writeFormat.parse(timestamp));
                            //  System.out.println("timestamp ok");
                        }
                    }
                    if (jsonObject.has("dataFrame")) {
                        String dataFrame = jsonObject.getString("dataFrame");
                        byte[] decodedString = Base64.getDecoder().decode(dataFrame.getBytes());
                        String msgDecode = new String(decodedString, "UTF-8");
                        obj.setDataFrame(msgDecode);
                    }
                    if (jsonObject.has("fcnt")) {
                        obj.setFcnt(jsonObject.getInt("fcnt"));
                        //System.out.println("fcnt ok");
                    }
                    if (jsonObject.has("freq")) {
                        obj.setFreq(jsonObject.getInt("freq"));
                        //System.out.println("freq ok");
                    }
                    if (jsonObject.has("rssi")) {
                        obj.setRssi(jsonObject.getInt("rssi"));
                        rssi = obj.getRssi();
                        //System.out.println("rssi ok");
                    }
                    if (jsonObject.has("session_id")) {
                        obj.setSession_id(jsonObject.getString("session_id"));
                        //System.out.println("session id ok");
                    }
                    if (jsonObject.has("port")) {
                        obj.setPort(jsonObject.getInt("port"));
                        //System.out.println("port ok");
                    }
                    if (jsonObject.has("snr")) {
                        obj.setSnr(jsonObject.getDouble("snr"));
                        snr = obj.getSnr();
                        //System.out.println("snr ok");
                    }
                    if (jsonObject.has("sf_used")) {
                        obj.setSf_used(jsonObject.getInt("sf_used"));
                        //System.out.println("sf used ok");
                    }
                    if (jsonObject.has("dr_used")) {
                        obj.setDr_used(jsonObject.getString("dr_used"));
                        // System.out.println("dr used ok");
                    }
                    if (jsonObject.has("decrypted")) {
                        obj.setDecrypted(jsonObject.getBoolean("decrypted"));
                        //System.out.println("decrypted ok");
                    }
                    if (jsonObject.has("gtw_info")) {
                        JSONArray array = jsonObject.getJSONArray("gtw_info");

                        for (int i = 0; i < array.length(); i++) {
                            JSONObject object = array.getJSONObject(i);
                            Gtw_info gtw = null;
                            gtw = new Gtw_info();

                            if (object.has("gps_tmst")) {
                                gtw.setGps_tmst(object.getLong("gps_tmst"));
                                // System.out.println("gtw tmst ok");
                            } else {
                                gtw.setGps_tmst(null);
                            }

                            if (object.has("gtw_id")) {
                                gtw.setGtw_id((String) object.get("gtw_id"));
                                //  System.out.println("gtw id ok");
                            } else {
                                gtw.setGtw_id(null);
                            }
                            if (object.has("snr")) {
                                gtw.setSnr(object.getDouble("snr"));
                                snr_gtw = gtw.getSnr();
                                //System.out.println("gtw snr ok");
                            } else {
                                gtw.setSnr(null);
                            }
                            if (object.has("rssi")) {
                                gtw.setRssi(object.getInt("rssi"));
                                rssi_gtw = gtw.getRssi();
                                // System.out.println("gtw rssi ok");

                            } else {
                                gtw.setSnr(null);
                            }

                            if ((snr_gtw.equals(snr))) {
                                if (rssi_gtw.equals(rssi)) {
                                    obj.setGateway(array.getJSONObject(i).getString("gtw_id"));
                                    // System.out.println("gateway ok");
                                }
                            }
                            obj.adicionarGtw_info(gtw);
                        }
                    }
                    obj.setDeveui("be7a04000000008e");
                    String sql_last_id = "Select max(id) from Objeto";
                    EntityManager em = EntityManagerUtil.getEntityManager();
                    List lista = em.createQuery(sql_last_id).getResultList();

                    for (Object l : lista) {
                        id_consultado = (Long) l;
                    }

                    if (id_consultado == null) {
                        id_consultado = 0000000000L;
                    }
                    if ((id_consultado != obj.getid()) && (obj.getid() > id_consultado)) {
                        try {
                            em.getTransaction().begin();
                            em.persist(obj);
                            em.getTransaction().commit();
                            System.out.println("Objeto persistido com sucesso!");

                        } catch (Exception e) {
                            if (em.getTransaction().isActive() == false) {
                                em.getTransaction().begin();
                            }
                            em.getTransaction().rollback();
                            System.out.println("Erro ao persistir: " + Util.getMensagemErro(e));
                        }
                    } else {
                        System.out.println("nao insere");
                    }

1 answer

1

You need to use the class Timertask.

The ideal is to have a class on the side that extends TimerTask. In it, you must implement the method run(), which is the code you want to run.

class TarefaScheduler extends TimerTask {
    public void run() {
       //sua lógica que deverá ser executada
    }
}

Then, at some point in your project, you should instantiate a class object Timer and invoke his method scheduleAtFixedRate(), which takes three parameters in order: the task to be executed, the delay before it is executed and the interval at which it must be executed, both values in milliseconds.

//em algum ponto do seu código
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TarefaScheduler(), 0, 300_000); //300_000 ms = 5 minutos
  • I was using Timer, but I need something that has an asynchronous call. With Timer the code was only executed when the application was opened. I need to run this code 24/7...@Statelessdev

  • If you need something running independently of your application, then you may need another service, small, with the minimum necessary to run that timer, access your bank and record what you need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.