不在 JDA 中创建另一个对象就无法取消定时器任务

问题描述 投票:0回答:0

主要是,我正在编写一个 discord 机器人,它获取任何加密货币的价格(与 CoinMarketCapAPI 集成)并将价格返回给用户。我创建了一个命令,在触发时在其关闭时间(格林威治标准时间上午 12 点或英国时间晚上 9 点)发送比特币价格,但是当我尝试取消它时,价格仍然在给定时间显示。

我知道我做错了什么,但我脑子里没有明确的解决方案: 当我调用警报类时,它会创建一个带有自己计时器的对象,但我无法在另一个不和谐命令上访问同一个对象,我必须创建一个不同的。

//Command Handler Class
else if (command.equals("bitcoin-scheduled-alert-start")) {
            ScheduledAlert scheduledAlert = new ScheduledAlert(event.getTextChannel());
            scheduledAlert.start(LocalTime.of(21,00, 00));
            event.reply("The daily closing price of Bitcoin will be displayed from now on!").queue();

        } else if (command.equals("bitcoin-scheduled-alert-stop")) {
            ScheduledAlert disabledScheduledAlert = new ScheduledAlert(event.getTextChannel());
            disabledScheduledAlert.stop();
            event.reply("The current scheduled alert has been stopped!").queue();
        }
public class ScheduledAlert { //Bitcoin update at every candle close (12 am GMT [9 pm BRT])
    private final Timer timer;
    private TimerTask task;
    private final TextChannel channel;
    private final String symbol;

    public ScheduledAlert(TextChannel channel) {
        this.channel = channel;
        this.symbol = "BTC";
        this.timer = new Timer();
    }

    public void start(LocalTime time) { //Getting the time from BotCommands parameter
        // Cancel the task if it is already scheduled (NOT WORKING)
        if (task != null) {
            task.cancel();
        }

        task = new TimerTask() { //Start TimerTask
            @Override
            public void run() {
                System.out.println("Started");
                CryptoPrice cmcApi = new CryptoPrice(symbol); //Get Bitcoin price
                double price = cmcApi.getPrice(symbol);

                NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.US);
                String priceString = formatter.format(price);
                System.out.println((priceString));
                channel.sendMessage("The closing price of Bitcoin is " + priceString).queue();
            }
        };

        ZonedDateTime now = ZonedDateTime.now(ZoneId.of("America/Sao_Paulo")); //Sync date with time zone
        ZonedDateTime scheduledTime = ZonedDateTime.of(now.toLocalDate(), time, now.getZone());

        if (now.compareTo(scheduledTime) > 0) {
            scheduledTime = scheduledTime.plusDays(1); //If the command has been triggered after time in LocalTime, set it to next day at the set time
        }

        long delay = Duration.between(now, scheduledTime).toMillis();
        timer.schedule(task, delay, TimeUnit.DAYS.toMillis(1));
    }
     

    public void stop() {
        if (task != null) {
            task.cancel();
            task = null;
            System.out.println("Stopped");
        }
    }

有没有办法访问同一个对象?

java timertask discord-jda
© www.soinside.com 2019 - 2024. All rights reserved.