How to Execute a Piece of Code Only Once

How to execute a piece of code only once?

Use global static objects with constructors (which are called before main)? Or just inside a routine

static bool initialized;
if (!initialized) {
initialized = true;
// do the initialization part
}

There are very few cases when this is not fast enough!


addenda

In multithreaded context this might not be enough:

You may also be interested in pthread_once or constructor function __attribute__ of GCC.

With C++11, you may want std::call_once.

You may want to use <atomic> and perhaps declare static volatile std::atomic_bool initialized; (but you need to be careful) if your function can be called from several threads.

But these might not be available on your system; they are available on Linux!

Execute a code only one time in C

A simple code using a static variable.

static bool once = false;

if (once == false)
{
once = true;
// do your "once" stuff here
}

Efficient way of having a function only execute once in a loop

I would use a decorator on the function to handle keeping track of how many times it runs.

def run_once(f):
def wrapper(*args, **kwargs):
if not wrapper.has_run:
wrapper.has_run = True
return f(*args, **kwargs)
wrapper.has_run = False
return wrapper

@run_once
def my_function(foo, bar):
return foo+bar

Now my_function will only run once. Other calls to it will return None. Just add an else clause to the if if you want it to return something else. From your example, it doesn't need to return anything ever.

If you don't control the creation of the function, or the function needs to be used normally in other contexts, you can just apply the decorator manually as well.

action = run_once(my_function)
while 1:
if predicate:
action()

This will leave my_function available for other uses.

Finally, if you need to only run it once twice, then you can just do

action = run_once(my_function)
action() # run once the first time

action.has_run = False
action() # run once the second time

How to run a piece of code only once everyday?

This will work for you. Call this function from splash

checkIsTodayVisit() async {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

SharedPreferences preferences = await _prefs;
String lastVisitDate = preferences.get("mDateKey");

String toDayDate = DateTime.now().day.toString(); // Here is you just get only date not Time.

if (toDayDate == lastVisitDate) {
// this is the user same day visit again and again

} else {
// this is the user first time visit
preferences.setString("mDateKey", toDayDate);
}
}

Function in JavaScript that can be called only once

If by "won't be executed" you mean "will do nothing when called more than once", you can create a closure:

var something = (function() {
var executed = false;
return function() {
if (!executed) {
executed = true;
// do something
}
};
})();

something(); // "do something" happens
something(); // nothing happens

In answer to a comment by @Vladloffe (now deleted): With a global variable, other code could reset the value of the "executed" flag (whatever name you pick for it). With a closure, other code has no way to do that, either accidentally or deliberately.

As other answers here point out, several libraries (such as Underscore and Ramda) have a little utility function (typically named once()[*]) that accepts a function as an argument and returns another function that calls the supplied function exactly once, regardless of how many times the returned function is called. The returned function also caches the value first returned by the supplied function and returns that on subsequent calls.

However, if you aren't using such a third-party library, but still want a utility function (rather than the nonce solution I offered above), it's easy enough to implement. The nicest version I've seen is this one posted by David Walsh:

function once(fn, context) { 
var result;
return function() {
if (fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}

I would be inclined to change fn = null; to fn = context = null;. There's no reason for the closure to maintain a reference to context once fn has been called.

Usage:

function something() { /* do something */ }
var one_something = once(something);

one_something(); // "do something" happens
one_something(); // nothing happens

[*] Be aware, though, that other libraries, such as this Drupal extension to jQuery, may have a function named once() that does something quite different.

Run specific code within a function only once

Make driver a static member of your class. Check it for null.

static ChromeDriver driver;
public static void Order_go(string url, string name)
{
if (driver == null) { driver = new ChromeDriver(); }

driver.Url = (url);
IWebElement b_login1 = driver.FindElement(By.Id("login"));
b_login1.SendKeys("aa");
IWebElement b_pass1 = driver.FindElement(By.Name("managerPw"));
b_pass1.SendKeys("123");
//Execute each time when it is called
}

I would caution you that ChromeDriver may not be thread safe.

How do I run some code only once in Dart?

There is no built-in functionality to prevent code from running more than once. You need some kind of external state to know whether it actually did run.

You can't just remember whether the function itself has been seen before, because you use a function expression ("lambda") here, and every evaluation of that creates a new function object which is not even equal to other function objects created by the same expression.

So, you need something to represent the location of the call.

I guess you could hack up something using stack traces. I will not recommend that (very expensive for very little advantage).

So, I'd recommend something like:

class RunOnce {
bool _hasRun = false;
void call(void Function() function) {
if (_hasRun) return;
// Set after calling if you don't want a throw to count as a run.
_hasRun = true;
function();
}
}

...
static final _runOnce = RunOnce();
void onUserLogin() {
_runOnce(handleInitialMessage);
}

It's still just a static global that can be accidentally reused.

Is is possible to make a method execute only once?

Sure!..

if(!alreadyExecuted) {
doTrick();
alreadyExecuted = true;
}

How can I run a piece of code only once in swift?

What you need is persistence between app launches. Fortunately, this exists and is provided with NSUserDefaults.

I would do something like the following in your app delegate didFinishLaunching method:

let hasLaunchedKey = "HasLaunched"
let defaults = UserDefaults.standard
let hasLaunched = defaults.bool(forKey: hasLaunchedKey)

if !hasLaunched {
defaults.set(true, forKey: hasLaunchedKey)
}

// Use hasLaunched

The first time you run the app, the key will not be in the defaults database and will return false. Since it is false, we save the value of true in the defaults database, and each subsequent run you will get a value of true.



Related Topics



Leave a reply



Submit