Execute specified function every X seconds
Use System.Windows.Forms.Timer.
private Timer timer1;
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 2000; // in miliseconds
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
isonline();
}
You can call InitTimer()
in Form1_Load()
.
Calling a method every x minutes
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(5);
var timer = new System.Threading.Timer((e) =>
{
MyMethod();
}, null, startTimeSpan, periodTimeSpan);
Edit - this answer is out of date. See https://stackoverflow.com/a/70887955/426894
Run function every 10 seconds
follow this :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addFirstSlide()
{
PowerPoint.Slide firstSlide = Globals.ThisAddIn.Application.ActivePresentation.Slides[1];
PowerPoint.Shape textBox2 = firstSlide.Shapes.AddTextbox(
Office.MsoTextOrientation.msoTextOrientationHorizontal, 50, 50, 500, 500);
textBox2.TextFrame.TextRange.InsertAfter("firstSlide");
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 1000;
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
addFirstSlide();
}
}
}
What is the best way to repeatedly execute a function every x seconds?
If your program doesn't have a event loop already, use the sched module, which implements a general purpose event scheduler.
import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc):
print("Doing stuff...")
# do your stuff
sc.enter(60, 1, do_something, (sc,))
s.enter(60, 1, do_something, (s,))
s.run()
If you're already using an event loop library like asyncio
, trio
, tkinter
, PyQt5
, gobject
, kivy
, and many others - just schedule the task using your existing event loop library's methods, instead.
Angular 6 run a function in every X seconds
Use interval
from rxjs
Here's how:
import { interval, Subscription } from 'rxjs';
subscription: Subscription;
...
//emit value in sequence every 10 second
const source = interval(10000);
const text = 'Your Text Here';
this.subscription = source.subscribe(val => this.opensnack(text));
...
ngOnDestroy() {
this.subscription.unsubscribe();
}
Alternatively, you can use setInterval
which is available as method on the Window Object. So you don't need to import anything to use it.
intervalId = setInterval(this.opensnack(text), 10000);
...
ngOnDestroy() {
clearInterval(this.intervalId);
}
Here's a SAMPLE STACKBLITZ for your ref.
flutter run function every x amount of seconds
build()
can and usually will be called more than once and every time a new Timer.periodic
is created.
You need to move that code out of build()
like
Timer? timer;
@override
void initState() {
super.initState();
timer = Timer.periodic(Duration(seconds: 15), (Timer t) => checkForNewSharedLists());
}
@override
void dispose() {
timer?.cancel();
super.dispose();
}
Even better would be to move out such code from widgets entirely in an API layer or similar and use a StreamBuilder
to have the view updated in case of updated data.
Is it possible to execute function every x seconds in python, when it is performing pool.map?
You can use a permanent threaded timer, like those from this question: Python threading.timer - repeat function every 'n' seconds
from threading import Timer,Event
class perpetualTimer(object):
# give it a cycle time (t) and a callback (hFunction)
def __init__(self,t,hFunction):
self.t=t
self.stop = Event()
self.hFunction = hFunction
self.thread = Timer(self.t,self.handle_function)
def handle_function(self):
self.hFunction()
self.thread = Timer(self.t,self.handle_function)
if not self.stop.is_set():
self.thread.start()
def start(self):
self.stop.clear()
self.thread.start()
def cancel(self):
self.stop.set()
self.thread.cancel()
Basically this is just a wrapper for a Timer
object that creates a new Timer
object every time your desired function is called. Don't expect millisecond accuracy (or even close) from this, but for your purposes it should be ideal.
Using this your example would become:
finished = 0
def make_job():
sleep(1)
global finished
finished += 1
def display_status():
print 'finished: ' + finished
def main():
data = [...]
pool = ThreadPool(45)
# set up the monitor to make run the function every minute
monitor = PerpetualTimer(60,display_status)
monitor.start()
results = pool.map(make_job, data)
pool.close()
pool.join()
monitor.cancel()
EDIT:
A cleaner solution may be (thanks to comments below):
from threading import Event,Thread
class RepeatTimer(Thread):
def __init__(self, t, callback, event):
Thread.__init__(self)
self.stop = event
self.wait_time = t
self.callback = callback
self.daemon = True
def run(self):
while not self.stop.wait(self.wait_time):
self.callback()
Then in your code:
def main():
data = [...]
pool = ThreadPool(45)
stop_flag = Event()
RepeatTimer(60,display_status,stop_flag).start()
results = pool.map(make_job, data)
pool.close()
pool.join()
stop_flag.set()
Javascript - Execute function every x seconds, but only execute function 3 times
Use setInterval and keep a counter on each run then, clear the interval when the count gets large enough.
(function() {
var c = 0;
var timeout = setInterval(function() {
//do thing
c++;
if (c > 2) {
clearInterval(timeout);
}
}, 10000);
})();
http://codepen.io/anon/pen/bNVMQy
Related Topics
How to Run a .Net Console Application in the Background
Best Way to Display Decimal Without Trailing Zeroes
How to Render a Razor View to a String in ASP.NET MVC 3
How Can a Windows Service Start a Process When a Timer Event Is Raised
Accessing Google Spreadsheets with C# Using Google Data API
What Represents a Double in SQL Server
Linq List of Lists to Single List
Getting Day Suffix When Using Datetime.Tostring()
How to Round to the Nearest Whole Number in C#
How to Make C# Switch Statement Use Ignorecase
Routing: the Current Request for Action [...] Is Ambiguous Between the Following Action Methods
Using Layers and Bitmask with Raycast in Unity
What Really Happens in a Try { Return X; } Finally { X = Null; } Statement
Does the Use of the "Async" Suffix in a Method Name Depend on Whether the 'Async' Modifier Is Used