Skip to content

Getting Started

Caio Lima edited this page Jul 17, 2024 · 5 revisions

Installing PTymer

You can easily install PTymer with Python's default package installer (pip on Windows, pip3 on Linux/MacOS):

pip install ptymer

This also might install its dependencies, but you can install them manually too:


Starting with classes

PTymer's Timer, HourGlass, and Alarm are classes, which means you must instantiate them before use. They're quite simple but have many particularities, and you should be aware of them. Here are more examples of simple usage:

Timer

from ptymer import Timer

def foo():
    print('foo')

tm = Timer(visibility=True)
tm.start()
foo()
tm.stop()

This piece of code should tell you the runtime of foo(). In fact, everything between start and stop.

HourGlass

from ptymer import HourGlass

def action(*args):
    # your code here

hg = HourGlass(seconds=60, target=action, args=(*,), visibility=True)
hg.start()
# rest of the code

Within the specified time (60 seconds), the function action will be executed side by side with the main code.

Alarm

from ptymer import Alarm

def send_email(cc, subject, content):
    # your code here

al = Alarm(schedules=['10:00:00'], target=send_email, args=(cc, subject, content,), visibility=True)
al.start()

With these couple of lines, it's set to the next 10 A.M. to execute the send_email function. You can make it last forever (every 10 A.M.) with the persist=True statement.

All of these classes allow you to instantiate and start them in one line also:

import ptymer
tm = ptymer.Timer(visibility=True).start()


⚠️ Important Warning

Attention: Alarm and HourGlass classes use multiprocessing, which is a native Python package whose documentation can be found here. Due to its process-based parallelism, there are a few things you must do to ensure that everything's fine with your code. First of all, you should protect its execution by checking __name__:

from ptymer import *

def foo():
    # your function code here

if __name__ == "__main__":
    foo()
    # rest of the code here

Also, when using pyinstaller or another way to produce an executable, you must handle main-process freezing. This ensures proper initialization and prevents issues related to process spawning and platform-specific behavior, making your executable robust and functional across different environments:

from multiprocessing import freeze_support

if __name__ == '__main__':
    freeze_support()
    # rest of your code here

You can find more details of these issues on the multiprocessing topic.

Clone this wiki locally