#ScheduledExecutorService

1 messages ยท Page 1 of 1 (latest)

merry carbon
#
// Try-resource
        try (ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor()){
            exec.scheduleAtFixedRate(new Runnable() {
                                         @Override
                                         public void run() {
                                                System.out.println("running");
                                         }
                                     }
                    , 0, 1, TimeUnit.SECONDS);
        }

I have this ScheduledExecutorService, but I'm not sure how I can tell if it's working as I don't see anything printed in my terminal. I assume because it's running on another thread it's printing elsewhere?

finite bloomBOT
#

<@&987246399047479336> please have a look, thanks.

finite bloomBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.

#

Here is an AI assisted attempt to answer your question ๐Ÿค–. Maybe it helps! In any case, a human is on the way ๐Ÿ‘. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#

@Override
public void run() {
// code to be executed repeatedly
}
}, initialDelay, period, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}


The `ScheduledExecutorService` is a class in the `java.util.concurrent` package that provides methods for scheduling tasks to be executed at fixed intervals or after a delay. In this example, we are using the `newSingleThreadScheduledExecutor()` method from the `Executors` class to create a single-threaded executor service.

Inside the try-with-resources block, we call the `scheduleAtFixedRate()` method on the executor service. This method takes four parameters:
1. A `Runnable` object that defines the task to be executed repeatedly.
2. The initial delay before the first execution of the task.
3. The period between successive executions of the task.
4. The time unit for specifying the initial delay and period.

In this example, we are using an anonymous inner class to define the `Runnable` object. Inside the `run()` method of this object, we can write our code that needs to be executed repeatedly.

If any exception occurs during the execution of the scheduled task, it will be caught by the catch block and printed using `e.printStackTrace()`.
soft temple
#

System.out is always the same, it doesn't change per thread

#

meaning it's not running

merry carbon
#

do you see anything that may explain why it's not running in that codeblock?

tidal crown
#

the code seems fine for me, might need to supply more context

merry carbon
#
public class Main {
    public static void main(String[] args) throws LoginException {

        // Load the .env file
        File file = new File(".env");
        String absolutePath = file.getAbsolutePath();

        // Get the absolute path of the .env file using the current working directory
        Dotenv config = Dotenv.configure().directory(absolutePath).filename(".env").load();
        String token = config.get("TOKEN");

        // Create a database connection
        DB db;

        MyBot bot;
        try {
            db = new DB("scheduledServers.db");
            bot = new MyBot(token, db);
        }
        catch (LoginException e) {
            throw new LoginException(e.getMessage());
        }

        // Try-resource
        try (ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor()){
            exec.scheduleAtFixedRate(new Runnable() {
                                         @Override
                                         public void run() {
                                                System.out.println("running");
                                         }
                                     }
                    , 0, 1, TimeUnit.SECONDS);
        }
    }
}
finite bloomBOT
# merry carbon ```java public class Main { public static void main(String[] args) throws Lo...

Detected code, here are some useful tools:

Formatted code
public class Main {
  public static void main(String[] args) throws LoginException {
    // Load the .env file
    File file = new File(".env");
    String absolutePath = file.getAbsolutePath();
    // Get the absolute path of the .env file using the current working directory
    Dotenv config = Dotenv.configure().directory(absolutePath).filename(".env").load();
    String token = config.get("TOKEN");
    // Create a database connection
    DB db;
    MyBot bot;
    try {
      db = new DB("scheduledServers.db");
      bot = new MyBot(token, db);
    } catch (LoginException e) {
      throw new LoginException(e.getMessage());
    }
    // Try-resource
    try (ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor()) {
      exec.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
          System.out.println("running");
        }
      }
      , 0, 1, TimeUnit.SECONDS);
    }
  }
}
soft temple
#

Wait, doesn't the try with resources just destroy the exec instance

#

before the runnable is run

#

that's what try with resources does

#

it doesn't wait

tidal crown
#

yeah true

merry carbon
soft temple
#

yes

merry carbon
#

ahhhh alright that makes alot of sense lol

tidal crown
#

you would need to add join one the future and check if its working

soft temple
#

Or don't use a try with resources and store it as a instance variable somewhere

#

and close manually

tidal crown
#

or what the method is called

#

not sure rn

merry carbon
tidal crown
#

actually the default get will wait

soft temple
#

yuh

merry carbon
#

might be a funny question, but when would it make sense the close it?

#

if I shut it down at the end of my main it just basically never runs

#

I could put it in like an infinite while loop lol

tidal crown
#

when the application should shutdown or the fucntionality is not used anymore

merry carbon
#

acc I always need it

#

so ig there's no point in freeing the resources

uneven flame
merry carbon
tidal crown
#

but I think thats a non-deamon thread

#

so you need to close all tasks running currently

#

or otherwise the jvm will stay alive

#

until those finished