You Don't Love Systemd Timers Enough (blog.tjll.net)

188 points by yacin 7 hours ago

66 comments:

by thomashabets2 2 hours ago

I haven't used systemd timers enough to disagree, but

> Ambiguous $PATH settings make cron script execution difficult to predict.

What makes you say that? You can set the PATH right in the crontab. Is that harder to "predict" than it being set in /etc/bashrc, ~/.bashrc, ~/.profile, ~/.bash_profile, /etc/systemd/…, or wherever else?

> You might feel cool knowing the scheduling grammar by heart

I've used Linux since 1994 and I don't know it by heart. But luckily it's pre-printed in the crontab as comments:

    # For more information see the manual pages of crontab(5) and cron(8)
    # 
    # m h  dom mon dow   command
You just put numbers aligned with the titles.

The rest of the complaints, sure. Next time I need a cronjob, I'll try it out.

by jeroenhd an hour ago

Having had to work on an application supposedly supporting cron expressions: the numbers are just the basic parts of the language.

When someone inputs something ridiculous like "5,3/4 4-8,11 1 4,5,6,9-11 */2" you get to enjoy the fun of reverse engineering what they meant (it's never what they actually wrote).

And that's before you get to all the extensions supported in some cron environments (but not all).

I find systemd timers a lot more manageable. Things like having control over whether or not long-running jobs are allowed to overlap and the ability to run tasks between start-finish rather than a fixed time window are major improvements for me. At some point my VPS went down because the backup job ran into some kind of symlink loop and cron just kept spawning more and more backup tasks even though none of them finished.

Having to re-write commands and scripts because CRON had its own special PATH was also a pain point, but the same can be true for some types of systemd timers. But: you can execute those timers manually if you want instead of updating the crontab to trigger in 30 seconds and simply waiting.

by jerf an hour ago

"You just put numbers aligned with the titles."

That is not a fair summarization of their point because that is not the grammar. There's commas, slashes, asterisks, combinations, and then if you want randomization you need to put it in the command itself because cron can't do it. (Some crons can, but it's not a general capability of cron.) Writing a non-trivial cron spec is not easy.

by nailer 10 minutes ago

> But luckily it's pre-printed in the crontab as comments

That's true, but most people don't know the numbered manual sections, so they get the docs for the cron table command not the cron table config file.

by jchw an hour ago

The main nice thing about the environment in systemd is that it is standard and mostly a blank slate, whereas at least for me I was always getting bit by the fact that the environment in Crontab was completely different from say, the environment inherited by supervisord or sysvinit scripts. In systemd the actual unit that gets executed is the same regardless of what triggers it, so there is no gap.

That does require you to still know what the default environment is, but it is a mostly completely clean environment, without any influence from any shell.

I'd have to concur that I agree this is an advantage of systemd.

by egorfine 31 minutes ago

> I've used Linux since 1994

Same here.

We are now considered old and therefore irrelevant. The new generation uses timers and couldn't care less about cron that has served us just fine for decades.

I use cron and my general attitude towards LP and systemd is very similar to the attitude of LP and systemd to us.

by NikhilVerma 3 hours ago

I have a Canon printer, I actually can't trust that their print nozzle won't get jammed up after sitting idle for a while. So I had claude setup a systemd script to print a picture of my dog every week, I ensure it has enough CMYK spectrum to stress the printer. Its a nice surprise every monday as I sit on my desk to see a sudden picture pop up from the printer :)

by tdeck 3 hours ago

I wish printers could have a mode like this to print random images from an album, or a calendar, rather than wastefully draining ink into a sponge every few days.

If nothing else, maybe it could be some kid's high school science fair project idea.

by magicalhippo 2 hours ago

Dad had an Deskjet 720 or something like that.

It sat unused and powered off for a couple of years after he passed, until I needed a color print.

Didn't do anything but hook it up to power and print. Took about 1/5 of a page until all colors were back in action, after that it printed about 20 pages flawlessly.

by ThePowerOfFuet 2 hours ago

Laser printers are your friend. The savings on consumables alone will make it pay for itself.

by RicoElectrico 2 hours ago

I was about to recommend a cheap OKI LED color printer (I think C322dn); alas they withdrew from consumer market :/ The colors are super nice and uniform, even if the maximum resolution is only 600 dpi - and the toner won't dry out, which was my brother's crucial purchase criterion; we had HP inkjet clogged more than once.

by gchamonlive 3 hours ago

Moved from cronie to systemd timers because they are resilient to system startup times. My backup strategy is to create a borg archive entry every day at a fixed time. With cronie the system needs to be running at the scheduled time, but systemd timer tolerates this and runs the service as soons as the system is available.

Btw this is my repo for the backup automation: https://github.com/gchamon/borg-automated-backups

by mid-kid 3 hours ago

Cronie has a mechanism for this, called "anacron", which is called hourly by cron (on my system, /etc/cron.hourly/0anacron), and performs all the /etc/cron.{daily,weekly,monthly} tasks, no matter if the earliest possible schedule was missed (and with a configurable random delay). You can modify /etc/anacrontab to create custom schedules.

To do this at the user level, you can add something like "@hourly anacron -t /path/to/anacrontab -S /path/to/spooldir" to the user's crontab, though I've never tried this.

Many cron implementations have a similar mechanism.

by michaelcampbell 24 minutes ago

> With cronie the system needs to be running at the scheduled time, but systemd timer tolerates this and runs the service as soons as the system is available.

Cronie doesn't have a `@reboot` meta-trigger?

by newsoftheday 2 hours ago

I'm sorry, I tried Googling the word "tolates" but I can't find any definition that makes sense?

> runs the service as soons as the system is available.

cron has the @reboot option which I use for a few scripts and works great.

by kayson 2 hours ago

I love systemd timers! I've slowly moved all of my ansible-deployed cron jobs to timers (now just an ansible copy!). The integration with journalctl, especially in a newer OS like Debian 13 where syslog is gone, is really nice. It's also really nice to be able to start the service manually for debug. Having a cron job that didn't work was an annoying exercise in copy/pasting or writing an extra shell script. Don't even get me started on the black hole of cron job stdout. I can monitor systemd services like I already do and get a notification on failure.

I've noticed more and more open source projects recommending timers as a deployment method and I think that's great!

by egorfine 29 minutes ago

> more and more open source projects recommending timers

I am perfectly happy with projects recommending timers as long as I can ignore them and use cron.

by stryan 3 hours ago

Timers can work with arbitrary units (not just a similarly-named service unit) so they can be surprisingly flexible. I have a timer on my servers that starts a backup.target that fires off a full "restic backup","restic prune", "restic forget" backup cycle each morning with randomized start times and notifications. The actual restic-* units are Podman Quadlets so the whole setup runs agnosticaly of what's on the server, just as long as it has Podman and Systemd installed.

I will admit thought, timers are up there in terms of being the clunkiest systemd unit type to use on a regular basis. I get why they're split up into two files and require different start vs enable syntax's, but man sometimes I just want to create a file that runs a script and be done with it.

by 9dev an hour ago

I feel like systemd units could need a layer of abstraction above them, so instead of editing the files manually, a tool would do it, some kind of declarative CLI or something. Probably not really a concern in the age of LLMs anymore, but it feels just slightly too tedious every time.

by esperent 3 hours ago

Why do you randomize your backup times?

by egorfine 20 minutes ago

We have used cron perfectly fine for decades and it served us well within its very clear limitations.

But now obviously we were so blind and wrong all this time and the only true solution is of course systemd.

by bakugo a minute ago

Has it actually served you well? Because it hasn't served me well at all.

I am not the biggest fan of systemd, but today I will always reach for a systemd timer over cron simply due to the sheer amount of bad experiences I've had with cron. Hours upon hours wasted trying to troubleshoot crons that weren't working due to some stupid obscure issue, having to use dirty hacks to monitor for success or retry failed jobs.

A few years ago I was trying to run a very simple bash script with cron and the script just died halfway through for no reason. Nothing in logs, worked fine when run directly, but in cron it just stopped halfway through a loop. Never figured out the cause, just gave up and used a timer instead, which worked fine. Never touched cron again after that.

The ease and convenience of monitoring and troubleshooting alone are worth switching over.

by bigbuppo 15 minutes ago

Thank Lennart you degenerate apostates are finally starting to see the light of His glorious creation. Hallowed be thy systemd-journald.

by progforlyfe 26 minutes ago

This is a very good intro to systemd timers -- I think you convinced me to finally start using them. Love the "list-timers" thing as well. With cron, it never seemed easy to me to get a picture of all the cron jobs running on a box. I'd need to check crontab for all users, as well as /etc/cron.d/, as well as the daily/hourly/monthly directories.

And in fact I do have a use-case for needing to run something ~5 minutes after the system boots and then every ~12 hours onward from there. It's great that systemd timers has me covered!

by hombre_fatal 4 hours ago

NixOS comes with systemd, so I've been using it as a first-class part of managing stuff. It's great, especially coming from macOS' launchd.

Which makes it nice to distribute a tool for NixOS so that it can lean into systemd instead of as some bolted-on afterthought.

Makes me wonder what you'd do if you were distributing a lifecycle-heavy tool for Linux users in general since systemd isn't ubiquitous.

I use a systemd timer to run a monthly scrub for my btrfs pool. Kinda cool how you can do increasingly useful things like skip the next scheduled event if the user initiates a scrub, do or don't accumulate tasks if you have a monthly task but the machine was offline for 6 months -- or fold them into a single task, etc.

by Cyph0n 3 hours ago

+1, NixOS makes working with systemd a breeze. Defining units in Nix beats wrangling INI files.

  systemd.services.sync-recyclarr = {
    serviceConfig.Type = "oneshot";
    path = [ pkgs.podman ];
    script = ''
      podman exec -it recyclarr recyclarr sync radarr
      podman exec -it recyclarr recyclarr sync sonarr
    '';
  };
  systemd.timers.sync-recyclarr = {
    timerConfig = {
      OnCalendar = "daily";
      Persistent = true;
      Unit = "sync-recyclarr.service";
    };
    partOf = [ "sync-recyclarr.service" ];
    requires = [ "podman-recyclarr.service" ];
    wantedBy = [ "timers.target" ];
  };
by drunner 3 hours ago

Have you been defining them directly in your flake.nix file? I too am on nixos but I keep all my configurations in their native format and symlink them with nix, that way I can take and reuse that config on a non nixos system easily.

The problem I have found is that nixos doesn't seem to pickup and run systemd timers and services placed into the ~/.config/systems/user folder and additionally things like WantedBy=default.target have no effect.

So after I restart all my services manually on reboot I agree, systems timers are cool.

by frays 3 hours ago

I've been using Linux for over 20 years, systemd for over 10.

Yet there's always something new to learn and actually consider as another useful tool.

by egorfine 29 minutes ago

I'm using Linux for about 30 years and apparently we were all wrong using cron for decades.

by MarkusWandel 9 minutes ago

Does systemd ship with something to upgrade your cron jobs for you? That would be the friendly way. Write your old school cron jobs, and then a script that converts them to do things the systemd way, documenting its steps, i.e. I created this file and this is why. Friendly "I help you do things better" rather than standoffish "your way is obsolete, you need to do it our way". Oh wait. I get it. LLM agents can do exactly that for you can't they. Another way I'm behind the curve.

I have knocked together a systemd service or three based on google copypasta. But generally, for cron jobs, why make it complicated? One line in /etc/crontab and done. I generally call an encapsulation script that sets the right environment variables, uses absolute paths, captures stdout/stderr if required and so on. I just want the simplest possible way to launch that script on a schedule.

by sammy2255 2 hours ago

I've converted all my crons to systemd timers+services over the past year but cant help but think it's sort of.. less tangible than cron

Like imagine trying to explain systemd timers and services and unit files to a beginner.

by darkwater 2 hours ago

> Like imagine trying to explain systemd timers and services and unit files to a beginner.

I think it's... easier? Like "systemd is the place where your system manages all the processes it needs to run. Part of those processes can be run on a schedule, or on a timer, and you define them using this simple text file".

by chuckadams an hour ago

I believe one of the major distro lines (redhat or debian, I forget which) uses systemd-cron, where cron is just a thin wrapper around systemd. You get more power from writing the unit files directly, but if all you ever need is a simple cron job, you have the old interface still available.

by MathMonkeyMan 32 minutes ago

Yep, I use this for a @reboot job and a few regular jobs on my home server. I use user crontabs, so I can get around the "unknown shell/path/etc." by prefixing every job with

    /some/shell -l myjob.sh
or sometimes

    . ~/.profile && cd /some/where && ./job >>cron.log 2>&1
by mindcrime an hour ago

I haven't always been the biggest fan of systemd in some regards, but I will say that I mostly agree with this sentiment. I've almost completely quit using cron, and now favor systemd timers for scheduled jobs - at the "system" level anyway. I might still embed Quartz for scheduling that's scoped to a particular application or something.

Why? It's one of those fuzzy and somewhat hard to explain things. The systemd approach just maps more cleanly to my mental model of "how things should work" I guess. And maybe some of it is that I did indeed experience plenty of " Ambiguous $PATH settings make cron script execution difficult to predict" in the past, although it's not just that.

I won't sit here and claim that systemd timers are necessarily better than cron in any universal / objective sense. But they've won me over, for what it's worth.

by lanycrost 3 hours ago

systemd is complex on first view, but after using it you didn't want to use anything else. It's handy to manage everything using systemctl

by bjoli 16 minutes ago

I hard disagree. Previously I could use what I knew about Linux commands to read logs and administer the systemm. Systemctl knowledge does not generalize.

I have done scheme all my life, which is why I prefer shepherd. Not only is it in a syntax that i can use elsewhere, I get completion in Emacs.

by alyandon 3 hours ago

That and systemd having actually useful man pages.

by egorfine 24 minutes ago

Some people see it differently. As in: after using it they don't want to use it. I hate systemd with passion.

But that's because I'm old because obviously systemd-* is the only right way and everyone else who see things differently is a pundit.

by the_real_cher 2 hours ago

This is such a modern view. People used to HATE systemd when it first came out, but I always liked it and knew people would eventually come around and its nice to see they finally did!

by bigbuppo 14 minutes ago

That would assume I like systemd in the first place.

by ktm5j 4 hours ago

Oh I love them quite a lot! I use them to run all of our backup jobs, easy to set up and have never had an issue.

by jjgreen 7 hours ago

I've been almost convinced by systemd (and have switched to using it), but God the syntax of those service files is so ugly ...

by zamadatix 4 hours ago

Never thought I'd see hackers saying INI format looked ugly of all things. It's basic, sure, but that's a good thing for something meant to be easily editable by hand from any editor. Otherwise, it's just key value pairs in named sections, how ugly can it be about that?

by mrweasel 4 hours ago

There's definitely some weirdness to certain parts of systemd service files, but was a huge improvement over Upstart and the old SysV-style init scripts.

Over all I think Systemd get way to much criticism. You don't have to use all the parts, but if you care to go through the documentation you'll find interesting features such as journald log-shipping and systemd-machined which can manage containers and VMs.

by egorfine 23 minutes ago

As a passionate systemd hater I would say I do not agree. Cron syntax is worse.

by SEJeff 4 hours ago

Oh yes, because the well documented clean syntax of sys v init shell scripts was so nice.

If I never recall hacking in ulimit calls in the top of buggy shell scripts for crappy old services that done respect pam_limits it won’t be soon enough.

by linsomniac 2 hours ago

Hard disagree. Compared to an init script, with all its boilerplate, I'd take a systemd unit file.

by WesolyKubeczek 4 hours ago

Could have been worse.

Could have been YAML.

Could have been XML.

by whateveracct 4 hours ago

This is why I like NixOS. Defining systemd services in it is very neat.

by dmuth 32 minutes ago

> stdout and stderr output often ends up in a black hole

Ain't that the truth. Literally every crontab I've written for the last 10 years has had this in it:

2>&1 | logger -t cron-WHATEVER

...and that does a pretty good job of capturing anything that the script emits and making it easy to grep for in syslog the following morning.

But I'm still amazed at how many crontabs I run across that don't capture any output at all.

by pull_my_finger an hour ago

I'm fully ready to drink the "just let systemd do all the things" kool-aid, but I would love to see some sort of introductory/tutorial info into some of the things it can do other than services - i.e. containers and timers. I know man pages exist, but it would be nice if there was more scannable intro out there.

by htx80nerd an hour ago

btw that xz hack only effect systemd distros

by cmsj 2 hours ago

Is there a way yet to force-trigger a timer? There wasn't the last time I used them, which I found to be super annoying for testing them.

by Biganon 2 hours ago

It's covered in the article, you can simply start the unit that would be started by the timer.

Oh but it won't appear in the timer-specific logs, I guess...

by mkesper 2 hours ago

There's another big feature: You're not relying on the time zone to which the server was set (like with cron) but can explicitly specify a time zone:

https://www.freedesktop.org/software/systemd/man/latest/syst...

by 6031769 an hour ago

Of course you can do this trivially in cron as well. It is what the CRON_TZ variable is for.

by iso1631 4 hours ago

> humble systemd

by pwdisswordfishq 3 hours ago

That the same cannot be said of its maintainer is another matter.

by andrewstuart 3 hours ago

Even better is systemd socket activation.

by wmanley 3 hours ago

I design all my services expecting to receive sockets this way. It makes sandboxing easy as the service itself doesn't need network access to have a listening socket.

It's a shame docker never supported it. I feel like if they had got on board all those years ago there would be broad support across the software ecosystem for it and we wouldn't need half of these complicated iptables rules and proxies and service mesh. It would be a step towards a capability based system.

by interf4ce 3 hours ago

This is very interesting. I'm not sure what I'd use it for yet, but I imagine it could be useful for triggering ad hoc jobs over the network. Maybe have Home Assistant make a network call to kick off a daily back up when I leave the office at the end of a work day.

by sunshine-o 2 hours ago

This is actually something that I like in systemd.

I am dealing with mostly non systemd system: BSD, Alpine, termux On BSD anacron works well, but I do not why I am always running into problems with the cronie anacron implementation. And it is very hard to debug.

I would really like a simple modern cron/anacron alternative.

Cronicle looked cool but it is node.js, a bit heavy and being replace now by their new product called xyOps anyway.

by baggy_trough 2 hours ago

In decades of trying, I do not believe there was one time that I ever got a cron job to work properly in the first attempt. Systemd timers are a godsend.

by simoncion 21 minutes ago

You will love SystemD [0] timers until they fuck you over in an entirely inscrutable way and the SystemD maintainers don't care to either fix the problem or update the docs to warn of the shortcoming.

One of our customers called in with a production down incident caused by a full disk. We got a copy of the VM and took a look. Investigation revealed that / was full because /var/log was full and that our 'logrotate' timer unit that was scheduled to run once a day had run either exactly never or exactly once... I can't remember which. Further investigation revealed no difference in software load or configuration between this VM and a VM that had a functional logrotate timer unit. Exactly one VM out of hundreds of identical VMs at this site (and many multiples of that at other customer's sites) were affected by this. Advising the customer to clear out /var/log and reboot did not unstick 'logrotate', and none of the diagnostics or fixes we could find anywhere unstuck it. Once "systemd-crond" decided to never schedule this job ever again, it stuck to that decision.

After a lot of searching, we found a still-open bug report from a year or three prior where someone reported exactly the same symptoms and was scheduling a unit with pretty much the same set of unit configuration flags that we were using. The conversation from the core devs ran through the pattern that one gets used to seeing when one runs into SystemD bugs that are caused by extremely complex unanticipated interactions between parts of the project: "That's not a bug, only an idiot would want that to work.", "Oh, we don't document that that's not supposed to work?", "Wow, okay, yeah, I can see how that maybe should work. That it doesn't sure does seem weird.", "Having said that, I don't know if it's supposed to work, or if it's unsupported. Someone should really either document that or fix it."... and then the behavior is neither fixed nor documented. [1] Absent any actual explanation for the failure, we ended up swizzling the options in our 'logrotate' unit and praying that satisfied whatever gremlin arose from the depths to trouble our customer.

SystemD contains an enormous -and ever-growing- amount of accidental complexity, and has a set of core maintainers who are generally disinterested in either documenting the places where one or more complex systems bind together to cause stop-the-world problems or fixing the systems involved so that they don't bind up. It's a fine project until it's very, very suddenly not, and then you're absolutely SOL. If you're lucky, you can shuffle around what you're doing [2] and hope that avoids the problem. [3]

[0] Some folks use the spelling "SystemD" to mock the project. I use the spelling "SystemD" to distinguish between "the entire systemd project" and systemd(1). I do this because some folks will make a claim like "systemd is very, very small and self-contained. I don't understand why anyone would say otherwise.", but what they are actually saying is that systemd(1) is a fairly small program that doesn't do all that much when run as PID 1. It sucks minor amounts of ass that the project and the program it runs as PID 1 share the same name, but what can you do?

[1] No, I don't have a link to the open bug report. This was more than a year ago, so the bug ID has been long forgotten.

[2] The term of art for this practice is "wave a dead chicken at it".

[3] Plus, like, even disregarding the rest of my report... how in the hell do you design a cron that knows a job is scheduled to be run periodically, can tell you how long it has been since it last ran, but never manages to run it? To me, that's unforgivable. It's a "You had one job!"-tier cockup.

by 7e 28 minutes ago

systemd is great all around. Don’t listen to the boomers complaining about it because their cheese was loved.

Data from: Hacker News, provided by Hacker News (unofficial) API