There are many ways in which you could receive the desired effect, but to start off we need a function that we can call.
def save_datetime(file='date.txt', user=getpass.getuser()):
with open(file, 'a+') as f:
f.write('register: ' + user + '\t' + str(datetime.datetime.now().time()) + '\n')
We now need a function for the loop.
def threadingtime_every_sec(sec=60):
import threading, time
def loop():
while True:
save_datetime()
time.sleep(sec)
threading.Thread(target=loop).start()
I understand you don't want to use time.sleep() but because it runs a thread it isn't noticeable and so is run separately. The full script would be:
import datetime
import getpass
import threading
import time
def save_datetime(file='date.txt', user=getpass.getuser()):
with open(file, 'a+') as f:
f.write('register: ' + user + '\t' + str(datetime.datetime.now().time()) + '\n')
def threadingtime_every_sec(sec=60):
def loop():
while True:
save_datetime()
time.sleep(sec)
threading.Thread(target=loop).start()
if __name__ == '__main__':
threadingtime_every_sec(1)
I would thoroughly recommend this answer and this question as it gives you multiple ways - and a much better threading system using the Timer
function and a Class. The full script in your case would be:
import threading
import time
import getpass
import datetime
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.next_call = time.time()
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self.next_call += self.interval
self._timer = threading.Timer(self.next_call - time.time(), self._run)
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False
def save_datetime(file='date.txt', user=getpass.getuser()):
with open(file, 'a+') as f:
f.write('register: ' + user + '\t' + str(datetime.datetime.now().time()) + '\n')
if __name__ == '__main__':
RepeatedTimer(1, save_datetime)
This creates an example text file like this:
register: james 11:51:54.988595
register: james 11:51:55.988939
register: james 11:51:56.988767
If you don't want milliseconds replace str(datetime.datetime.now().time())
with datetime.datetime.now().strftime('%H:%M:%S')
.