简体   繁体   English

如何扩展在TimerTask中运行的方法。 必须接受字符串参数

[英]How to extend method run in TimerTask . Must accept string parameter

I have this code 我有这个代码

private void startActionPerformed(java.awt.event.ActionEvent evt) {                                      
    this.start.setBackground(Color.green);
    this.stop.setBackground(Color.lightGray);
    if (!stopped) {
        timer.cancel();
    }
    stopped = false;
    stato.setText("Avviato");
    timer = new Timer();
    if(giacRitardo>0)
        timer.schedule(S.run("argiacenze"), giacRitardo, giacRitardo);//parti dopo x secondi e itera ogni x secondi
    if(cliRitardo>0)
        timer.schedule(S.run("arclienti"), cliRitardo, cliRitardo);//parti dopo x secondi e itera ogni x secondi

// some other code //其他代码

and

class TaskSchedulato extends TimerTask {

    @Override
    public void run() {
        redirectSystemStreams();
        DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        URL sito = null;
        try {
            sito = new URL(sUrl + "?aggiornamento=arlingue");
        } catch (MalformedURLException ex) {
            System.out.println("Indirizzo del sito mal formato o inesistente");
        }
        URLConnection yc = null;
        try {
            yc = sito.openConnection();
        } catch (IOException ex) {
            System.out.println("Errore di connessione _ ");
        }
        BufferedReader in = null;
        try {
            in = new BufferedReader(
                    new InputStreamReader(
                            yc.getInputStream()));
        } catch (IOException ex) {
            Logger.getLogger(TaskSchedulato.class.getName()).log(Level.SEVERE, null, ex);
        }
        String inputLine;
        try {
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
        } catch (IOException ex) {
            Logger.getLogger(TaskSchedulato.class.getName()).log(Level.SEVERE, null, ex);
            dataErrore = new Date();
            System.out.println(sdf.format(dataErrore));
            System.out.println("Errore di connessione: " + dataErrore);
        }
        try {
            in.close();
        } catch (IOException ex) {
            Logger.getLogger(TaskSchedulato.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

and

TaskSchedulato S = new TaskSchedulato();

I need to extend the method run above, so that i can pass a string parameter to it. 我需要扩展上面运行的方法,以便我可以将字符串参数传递给它。 How can a do it. 怎么办呢。 I'm almost a newbye in java. 我几乎是Java的再见者。 So, please forgive me for the inexperience. 所以,请原谅我的经验。

Actually I receive the error: no suitable method found for run(String) method TimerTask.run() is not applicable (actual and formal argument lists differ in length) method MainForm.TaskSchedulato.run() is not applicable (actual and formal argument lists differ in length) 实际上,我收到错误消息:没有找到适合run(String)方法的合适方法方法TimerTask.run()不适用(实际和正式参数列表的长度不同)方法MainForm.TaskSchedulato.run()不适用(实际和形式参数)列表的长度不同)

Thank you in advance 先感谢您

This can be easily achieved with method overloading . 这可以通过方法重载轻松实现。

In short, method overloading is a language feature that allows to declare multiple methods with the same name, but different parameters. 简而言之,方法重载是一种语言功能,它允许声明多个具有相同名称但参数不同的方法。

Applied to your problem, instead of overriding the parent's run() method, just declare another run() method like this: 应用于您的问题,而不是覆盖父级的run()方法,只需声明另一个run()方法,如下所示:

public void run(String someInput) {
    /* ... */
}

Of course, you can call run() from within run(String) if that makes sense in your program: 当然,如果在程序中有意义,则可以从run(String)调用run()

public void run(String someInput) {
    /* Do something with someInput */
    run(); // Hand over to parent's run() method
    /* Maybe do some other stuff */
}

Depending on what you are trying to do, you might want to use both, method overloading as well as overriding. 根据您要尝试执行的操作,可能要同时使用方法重载和覆盖。 Some more context would be required to give more specific advice. 为了提供更具体的建议,还需要更多的背景信息。

I solved this way 我这样解决了

class TaskSchedulato extends TimerTask {
    String stringa;
    public TaskSchedulato(String stringa){
        this.stringa=stringa;
    }
    @Override
    public void run() {
    //code here
    }

Thanks to @onurbaysan for the answer in the thread below How to Pass Arguments to Timertask Run Method 感谢@onurbaysan在下面的如何将参数传递给Timertask Run方法的线程中的答案

@domdom, signature of timer.schedule is schedule(TimerTask task,long delay,long period) @ domdom,timer.schedule的签名为schedule(TimerTask任务,延迟长,周期长)

I already used it in my working version of the program 我已经在程序的工作版本中使用过它

private void startActionPerformed(java.awt.event.ActionEvent evt) {                                      
    this.start.setBackground(Color.green);
    this.stop.setBackground(Color.lightGray);
    if (!stopped) {
        timer.cancel();
    }
    stopped = false;
    stato.setText("Avviato");
    timer = new Timer();
    if(giacRitardo>0)
        timer.schedule(new TaskGiacenze(), giacRitardo, giacRitardo);
    if(cliRitardo>0)
        timer.schedule(new TaskClienti(), cliRitardo, cliRitardo);
    if(artRitardo>0)
        timer.schedule(new TaskArticoli(), artRitardo, artRitardo
    //..........

and

class TaskGiacenze extends TimerTask {

    @Override
    public void run() {
        redirectSystemStreams();
        DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        URL sito = null;
        try {
            sito = new URL(sUrl + "?aggiornamento=argiacenze");
        } catch (MalformedURLException ex) {
            System.out.println("Indirizzo del sito mal formato o inesistente");
        }
        URLConnection yc = null;
        try {
            yc = sito.openConnection();
        } catch (IOException ex) {
            System.out.println("Errore di connessione _ ");
        }
        BufferedReader in = null;
        try {
            in = new BufferedReader(
                    new InputStreamReader(
                            yc.getInputStream()));
        } catch (IOException ex) {
            Logger.getLogger(TaskGiacenze.class.getName()).log(Level.SEVERE, null, ex);
        }
        String inputLine;
        try {
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
        } catch (IOException ex) {
            Logger.getLogger(TaskGiacenze.class.getName()).log(Level.SEVERE, null, ex);
            dataErrore = new Date();
            System.out.println(sdf.format(dataErrore));
            System.out.println("Errore di connessione: " + dataErrore);
        }
        try {
            in.close();
        } catch (IOException ex) {
            Logger.getLogger(TaskGiacenze.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

but I had to create a class for each kind (one class for giacenze, another class for articoli etc.. etc...) instead of calling it as parameter. 但是我必须为每种类型创建一个类(一类用于giacenze,另一类用于青蒿等,等等。),而不是将其称为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM