Systemd Timer

Author:
Email: jonas.pfannschmidt at gmail.com
Date: 31/01/2021

I keep forgetting how to do systemd timers. To avoid having to Google it, I'll just put it here ;-)

The Code

/etc/systemd/system/my.timer

      
[Unit]
Description=Run daily at 8am

[Timer]
OnCalendar=*-*-* 8:00:00
Persistent=true

[Install]
WantedBy=timers.target
      
    

/etc/systemd/system/my.service

      
[Unit]
Description=Run my

[Service]
Type=oneshot
ExecStart=/usr/bin/my --parameter
      
    

Behavior of oneshot is similar to simple; however, the service manager will consider the unit up after the main process exits. Source

The service unit will be controlled by the timer unit. Therefore it is enough to start/enable the timer unit: sudo systemctl daemon-reload && sudo systemctl start my.timer && sudo systemctl enable my.timer

Ansible

This is how to do it in Ansible:

      
tasks:
- name: Create systemd timer
  copy:
    content: |
      [Unit]
      Description=Run daily at 8am

      [Timer]
      OnCalendar=*-*-* 8:00:00
      Persistent=true

      [Install]
      WantedBy=timers.target
    dest:
      /etc/systemd/system/my.timer
    mode: '0644'
    owner: root
    group: root
  become_user: root
  become: true

- name: Create systemd service
  copy:
    content: |
      [Unit]
      Description=Run my

      [Service]
      Type=oneshot
      ExecStart=my --param
    dest:
      /etc/systemd/system/my.service
    mode: '0644'
    owner: root
    group: root
  become_user: root
  become: true

- name: Activate systemd timer
  systemd:
    name: my.timer
    state: started
    enabled: yes
    daemon_reload: yes
  become_user: root
  become: true