How do I make my code run asynchronously and in real time or every time?

-3

I need to know how I can 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");
                    }
    
asked by anonymous 29.10.2018 / 19:59

1 answer

1

You need to use the TimerTask class.

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

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

So at some point in your project, you should instantiate an object of class Timer and invoke your method

29.10.2018 / 20:26