<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<p>I've been doing this for a while (and am using the approach on my
javaspecialists.eu website):</p>
<div style="background-color:#2b2b2b;color:#a9b7c6">
<pre style="font-family:'JetBrains Mono NL',monospace;font-size:30,0pt;">Executors.<span style="font-style:italic;">newSingleThreadScheduledExecutor</span>(
Thread.<span style="font-style:italic;">ofVirtual</span>().factory())</pre>
</div>
<p></p>
<p>It works very well indeed.<br>
</p>
<pre class="moz-signature" cols="72">Regards
Heinz
--
Dr Heinz M. Kabutz (PhD CompSci)
Author of "The Java™ Specialists' Newsletter" - <a class="moz-txt-link-abbreviated" href="http://www.javaspecialists.eu">www.javaspecialists.eu</a>
Java Champion - <a class="moz-txt-link-abbreviated" href="http://www.javachampions.org">www.javachampions.org</a>
JavaOne Rock Star Speaker
Tel: +30 69 75 595 262
Skype: kabutz
</pre>
<div class="moz-cite-prefix">On 2023/08/01 19:46, Alan Bateman
wrote:<br>
</div>
<blockquote type="cite"
cite="mid:fadaf9d5-d59b-7147-a5cb-b97b913d8996@oracle.com">On
01/08/2023 06:57, Formula Salt wrote:
<br>
<blockquote type="cite">Hi,
<br>
<br>
I am trying to use virtual threads together with the
ScheduledExecutorService but I am uncertain what is the best way
to do so. To use the ExecutorService with virtual threads we
would use Executors.newVirtualThreadPerTaskExecutor() but there
seems to be no equivalent method for the
ScheduledExecutorService.
<br>
<br>
Executors.newScheduledThreadPool(int, ThreadFactory) would
require pooling virtual threads which I believe is considered
bad practice.
<br>
Executors.newSingleThreadScheduledExecutor(ThreadFactory) only
allows for a single thread so tasks must execute sequentially.
<br>
<br>
The best way I've found so far is in this StackOverflow answer
(<a class="moz-txt-link-freetext" href="https://stackoverflow.com/a/76599122">https://stackoverflow.com/a/76599122</a>) which suggests using both
a single-threaded ScheduledExecutorService and
Executors.newVirtualThreadPerTaskExecutor(). This works but
perhaps the Executors API should directly support this
via Executors.newVirtualThreadPerTaskScheduledExecutor() ?
<br>
</blockquote>
<br>
Just to add to what Ron said is that it's an area that didn't
receive any feedback or come up during preview. As I think you've
figured out, delay can be implemented by wrapping the task so that
it sleeps before running, periodic with fixed delay can be done
with a loop + sleep, periodic at fixed rate by submitting a
delayed task with the time remaining after the previous run. So
not hard, and the main difference being that each delayed or
periodic task runs in its own virtual thread rather than a pooled
thread. There is higher priority work require on a more scalable
timer implementation and that might be the right time to look at
Executors factory methods.
<br>
<br>
-Alan.
<br>
</blockquote>
</body>
</html>