GithubHelp home page GithubHelp logo

tick's Introduction

clojars tests build bb compatible

tick

A Clojure(Script) & babashka library for dealing with time. Intended as a replacement for clj-time.

Based on Java 8 time (on the JVM) and js-joda (on JavaScript runtimes). We are considering an implementation based on Temporal, via Tempo when it is available.

Status

  • tick.core - stable

  • tick.alpha.interval - Alpha: Ready to use with the caveat that the API might still undergo minor changes. Note also that this part of tick is not being actively maintained at the moment (other than to keep existing tests passing). There are currently around 10 open tickets relating to intervals which no one is looking at. It may be maintained again in the future of course.

Should you use Tick for date-time work?

  • If you are just working on the JVM and are comfortable with the java.time API then raw interop will work just fine.

  • If you are working in a Javascript environment then seriously consider using cljc.java-time: Its build size will not adversely affect your users (unless in a highly constrained context such as a microcontroller). The reason is the native Date API is flawed

  • If you meet any of the following criteria, use cljc.java-time:

    • are creating cross-platform date-time logic

    • are not proficient in java.time and would like improved error messages

    • would rather not maintain type hints in your code

  • If you meet the criteria to use cljc.java-time but would like a more terse API and the benefits of e.g. (t/with-clock …​) but will not miss having every date-time recipe one google search away, then tick might be a good choice. Tick uses cljc.java-time so you can always drop to that if Tick is missing something you need.

  • Similar in aiming for a terse API, but jvm-only is clojure.java-time.

Usage

(require '[tick.core :as t])

;; Get the current time
(t/instant)

Top tips

java.time

In both Clojure and Clojurescript versions, tick is just calling through to java.time methods. Understanding the main entities of java.time is necessary to use tick. For example, one should know that there are 2 separate ways to measure amounts of time (Period and Duration), 3 ways to represent a point on the timeline (Instant, ZonedDateTime & OffsetDateTime) and so on.

Instants

Instants are not 'calendar-aware' - they just contain millis+nanos fields representing an offset from the Unix epoch. This means Instants have no method to get their year or month for example, because to do so would require a calendar (e.g. the Gregorian calendar).

However, the following does work in Tick: (t/year (t/instant)). To make that possible, tick first converts the Instant into a ZonedDateTime (which does have a calendar). Take note however that the zone of the ZonedDateTime will be the browser’s or jvm’s timezone. To be explicit about the zone required do this:

(-> (t/instant)
    (t/in "UTC")
    (t/year))

The other cases where calendar-awareness might come up is when formatting Instants to string or when shifting them by e.g. years/months, so Tick shows explanatory error messages in that case.

Singular vs Plural ?

As with java.time, any functions working with amounts of time (ie Durations or Periods), will have names which are in the plural. Functions that work with dates and times are singular. Knowing that, e.g. t/second vs t/seconds makes sense.

Install

Get the latest from Clojars and add to your project.clj, build.boot or deps.edn.

To use this from Clojurescript, you must have at least version 1.11.51. If using shadow-cljs, it must be at least version 2.19.3

If using cljsjs, add js-joda and js-joda-locale-en-us and js-joda-timezone to your dependencies as well.

For Clojurescript users of Tick, see docs/cljs.adoc, for some discussion around Clojurescript build size.

Here is a one-liner to drop into a node repl with tick:

clj -Sdeps '{:deps {org.clojure/clojurescript {:mvn/version "RELEASE" } tick/tick {:mvn/version "RELEASE"} henryw374/js-joda {:mvn/version "RELEASE"} }}' -m cljs.main  -re node  --repl

Here is how to get to a babashka (v 1.2.174+) repl with tick:

export BABASHKA_CLASSPATH=$(clojure -Spath -Sdeps '{:deps {tick/tick {:mvn/version "0.6.0"}}}')

bb

Development

Develop The Documentation Site

Build the html

make

make dev-docs-cljs to build the js for the site needs fixing.

=== Build a production version of the Documentation Site

The following is not working currently:

make release-docs-cljs

=== Develop Tick

clj -Atest-clj:test-cljs

 - To start testing clojurescript, follow instructions in the `cljs` ns.
 - To start testing clojure, follow instructions in the the `repl` ns.

See the .github dir to see instructions for CLI testing

=== Release

create a git tag.

`make install` (this installs in ~/.m2 - check that things look ok)

`make deploy`  - you need to have set up clojars credentials as per https://github.com/applied-science/deps-library

`git push origin new-tag-name`

== Acknowledgements

In particular, special credit to Eric Evans for discovering Allen's
interval algebra and pointing out its potential usefulness,
demonstrating a working implementation of Allen's ideas in
link:https://github.com/domainlanguage/time-count[his Clojure library].

Thanks also to my esteemed colleagues Patrik Kårlin for his redesign of
the interval constructor function, and Henry Widd for porting to cljc.

== References

* https://github.com/dm3/clojure.java-time
* https://clojuresync.com/emily-ashley/
* https://github.com/aphyr/tea-time
* https://github.com/sunng87/rigui

== Copyright & License

The MIT License (MIT)

Copyright © 2016-2021 JUXT LTD.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

tick's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tick's Issues

JSJoda is not defined

In latest tick release (0.4.16-alpha), running tests on ChromiumHeadless throws an error

HeadlessChrome 76.0.3803 (Mac OS X 10.14.5) ERROR
  Uncaught ReferenceError: JSJoda is not defined
  at target/test.js:69318:20

  ReferenceError: JSJoda is not defined
      at target/test.js:69318:20

The tests runs perfectly with 0.4.14-alpha, we use shadow-cljs for the build of the JS bundle and js-joda is correctly defined with npm with version "1.11.0", what's different in latest tick release that could induce that error?

pause / resume

(def foo
  (let [timeline (-> (periodic-seq (now) (seconds 2))
                     (timeline))]
    (schedule (fn [_] (println "foo")) timeline)))

(defn bar []
  (start foo (clock-ticking-in-seconds))
  (stop foo)
  (schedule/pause foo)
  (schedule/resume foo))

When pause foo for a while and resume it will instantly run foo many times, because of "missed" points of time while paused. It shouldn't work like that. It should start from the point of time when resume. So points of time during pause should be as launched. pause/resume is not usable at that moment, because of that issue. Unless i miss something.

Tick breaks clj -Stree

Repro:

$ echo '{:deps {tick {:mvn/version "0.4.7-alpha"}}}' > deps.edn
$ clj -Stree

Error:

Error printing tree. Invalid token: /cljs.java-time
java.lang.RuntimeException: Invalid token: /cljs.java-time
	at clojure.lang.Util.runtimeException(Util.java:221)
	at clojure.lang.EdnReader.interpretToken(EdnReader.java:285)
	at clojure.lang.EdnReader.read(EdnReader.java:171)
	at clojure.lang.EdnReader.readDelimitedList(EdnReader.java:766)
	at clojure.lang.EdnReader$SetReader.invoke(EdnReader.java:691)
	at clojure.lang.EdnReader$DispatchReader.invoke(EdnReader.java:554)
	at clojure.lang.EdnReader.readDelimitedList(EdnReader.java:757)
	at clojure.lang.EdnReader$MapReader.invoke(EdnReader.java:680)
	at clojure.lang.EdnReader.readDelimitedList(EdnReader.java:757)
	at clojure.lang.EdnReader$MapReader.invoke(EdnReader.java:680)
	at clojure.lang.EdnReader.read(EdnReader.java:145)
	at clojure.lang.EdnReader.read(EdnReader.java:111)
	at clojure.edn$read.invokeStatic(edn.clj:35)
	at clojure.edn$read.invoke(edn.clj:14)
	at clojure.tools.deps.alpha.util.io$slurp_edn.invokeStatic(io.clj:29)
	at clojure.tools.deps.alpha.util.io$slurp_edn.invoke(io.clj:22)
	at clojure.tools.deps.alpha.script.print_tree$run.invokeStatic(print_tree.clj:23)
	at clojure.tools.deps.alpha.script.print_tree$run.invoke(print_tree.clj:20)
	at clojure.tools.deps.alpha.script.print_tree$_main.invokeStatic(print_tree.clj:39)
	at clojure.tools.deps.alpha.script.print_tree$_main.doInvoke(print_tree.clj:26)
	at clojure.lang.RestFn.applyTo(RestFn.java:137)
	at clojure.lang.Var.applyTo(Var.java:702)
	at clojure.core$apply.invokeStatic(core.clj:657)
	at clojure.main$main_opt.invokeStatic(main.clj:317)
	at clojure.main$main_opt.invoke(main.clj:313)
	at clojure.main$main.invokeStatic(main.clj:424)
	at clojure.main$main.doInvoke(main.clj:387)
	at clojure.lang.RestFn.applyTo(RestFn.java:137)
	at clojure.lang.Var.applyTo(Var.java:702)
	at clojure.main.main(main.java:37)

tick/reset! tries to apply without varargs

The definition of tick/reset! is:

(defn reset! [at newval]
  (apply clojure.core/reset! (:*clock at) newval))

However clojure.core/reset! only takes two arguments, not varargs. This will fail at runtime because reset! is trying to apply on newval, which is not a sequence of values, e.g.

(tick/reset! (tick/atom (Instant/now))
             (Instant/now))
Execution error (IllegalArgumentException) at tick.core/reset! (core.cljc:745).
Don't know how to create ISeq from: java.time.Instant

A workaround is:

(tick/reset! (tick/atom (Instant/now))
             [(Instant/now)])

Extend IConversion to AtomicClock?

I think it makes sense for the AtomicClock record to implement the IConversion protocol. It is already extended to Clock, I think it should be on AtomicClock too? My workaround for now:

(extend-type AtomicClock
  tick/IConversion
  (inst [this] (tick/inst (.instant (tick/clock this))))
  (instant [this] (tick/instant (.instant (tick/clock this)))) ;; slightly redundant, but keeps with the pattern
  (offset-date-time [this] (tick/offset-date-time (.instant (tick/clock this))))
  (zoned-date-time [this] (tick/zoned-date-time (.instant (tick/clock this)))))

tick.interval/complement fails on meeting intervals

If the coll passed to tick.interval/complement contains any two intervals that meet?, it will attempt to create an interval with the beginning after the end and throw an exception:

(tick.interval/complement [(t/yesterday) (t/today)])
;;Exception: Interval must span between two times, the first must be before the second

I believed this could be fixed by changing the following lines here:

tick/src/tick/interval.cljc

Lines 666 to 667 in e777e93

(let [r (map (fn [[x y]] (new-interval (t/end x) (t/beginning y)))
(partition 2 1 coll))]

To

...
(let [r (->> coll
             (partition 2 1)
             (remove (fn [[x y]] (meets? x y))) ;;alternatively, clojure.core/keep could replace map
             (map (fn [[x y]] (new-interval (t/end x) (t/beginning y)))))]
...

If you are interested I can provide a PR with tests.

Edit:
To expand on this a little bit, it's unclear what the argument passed to complement should be, but it seems like mostly likely it should be an ordered disjoint interval sequence, which should allow for intervals which meet, as described above.

tick on shadow-cljs

Evaluating (require '[tick.alpha.api: as tick]) in a ClojureScript environment fails with this error:

The required namespace "cljsjs.js-joda" is not available, it was required by "java/time.cljs".

I tried adding an explicit dependency to cljsjs/js-joda {:mvn/version "1.9.2-0"} in my deps.edn, but that didn't have any effect.

some examples in the docs not printing out anything useful

(t/intersects? [(t/year)]
(t/inc (t/year)))

(def clk (t/atom))
(def clk2 (t/atom (t/<< (t/clock) (t/new-duration 5 :minutes))))
(t/reset! clk clk2)

(def clk (t/atom))
(def clk2 (t/atom (t/<< (t/clock) (t/new-duration 5 :minutes))))
(t/reset-vals! clk clk2)

(def clk (t/>> (t/clock) (t/new-duration 5 :minutes)))
(t/with-clock clk (t/time)) =>

no button :
(t/with (t/today) :day-of-month 1)

Define a print-method for AtomicClock

I get the following error when trying to print an AtomicClock

(tick/atom (tick/clock (Instant/now)))

Error printing return value (IllegalArgumentException) at clojure.lang.MultiFn/findAndCacheBestMethod (MultiFn.java:179).
Multiple methods in multimethod 'print-method' match dispatch value: class tick.core.AtomicClock -> interface clojure.lang.IDeref and interface clojure.lang.IRecord, and neither is preferred

You can see one possible resolution of this kind of issue here: https://gist.github.com/rwilson/34c88a97c6260a7dc703 (though note that in that case they are working with pprint).

It would probably be good to define print-method for the AtomicClock, though I'm not really sure what the expected printing should be? For the meantime, I've used this:

(let [meth (get-method print-method IDeref)]
  (defmethod print-method AtomicClock [v writer]
    (meth v writer)))

(tick/atom (tick/clock (Instant/now)))
=> #object[tick.core.AtomicClock 0x6ec9db72 {:status :ready, :val #time/instant"2019-12-01T18:53:30.744363Z"}]

It looks like work on this was started, but it might need to add a preference for IRecord?

tick/src/tick/core.cljc

Lines 724 to 729 in 4241aaa

#?(:clj
(do
(prefer-method print-method clojure.lang.IPersistentMap clojure.lang.IDeref)
(prefer-method print-method java.util.Map clojure.lang.IDeref))
;todo - for cljs
)

Convert Long to Duration

I miss being able to do (t/hours 2) and I find (t/new-duration i :hours) a little to verbose.

I can easily get what I want by extending java.lang.Long like:

(extend-protocol tick.core/ITimeLength
  java.lang.Long
  (hours [i] (t/new-duration i :hours)))

(t/hours 2) => #time/duration"PT2H"

Is there any downsides doing that? Could we include it in tick?

Thank you so much for creating tick and the underlying cljc.java-time!

Overlapping scheduled function calls - Can't stop schedule

I was trying to see the behavior when calls to a long-running scheduled function overlap. I thought it was working as expected: the scheduled function is called at every tick in the schedule even if another is running. However, I'm unable to stop the schedule. Code to reproduce the issue is below. The issue goes away when removing the Thread/sleep or reducing it to less than the schedule interval. Even calling stop during the sleep works.

For my use case, I'm working on preventing the scheduled function from doing any work when another is in progress so it's not really an issue for me. More just wondering if I'm doing something wrong here.

(require '[tick.schedule :as schedule])
(require '[tick.clock :as clock])
(require '[tick.timeline :as tl])
(require '[tick.core :as tick])

(defn wait [t]
  (println (format "waiting for 30s - %s" t))
  (Thread/sleep 30000)
  (println (format "done waiting - %s" t)))

(defn build-schedule [now]
  (let [evey-ten-secs (tl/periodic-seq now (tick/seconds 10))]
    (schedule/schedule wait
                       (tl/timeline evey-ten-secs))))

(def my-schedule
  (let [sch (build-schedule (clock/now))]
     (schedule/start sch (clock/clock-ticking-in-seconds))
     sch))

;; Wait a few seconds and then call:

(schedule/stop my-schedule)

A few errors using Tick on ClojureScript with Piggieback/NodeJS

Hi there,

I'm evaluating Tick (version 0.4.14-alpha) and I'm seeing a few errors on ClojureScript with Piggieback/NodeJS..

Could anyone help me out? Thanks!

(require '[tick.alpha.api :as t])
(require '[tick.timezone])

; works
(t/truncate (t/instant 1552786820310) :seconds)

; works
(t/format (t/truncate (t/instant 1552786820310) :seconds))

; error
(t/format :iso-instant (t/truncate (t/instant 1552786820310) :seconds))
; Execution error (RangeError) at (<cljs repl>:1) .
; Maximum call stack size exceeded

; error
(t/format :iso-zoned-date-time (t/truncate (t/instant 1552786820310) :seconds))
; Execution error (RangeError) at (<cljs repl>:1) .
; Maximum call stack size exceeded

; error
(t/in (t/truncate (t/instant 1552786820310) :seconds) "Europe/London")
; Execution error (Error) at (<cljs repl>:1) .
; unsupported ZoneId:Europe/London

; error
(t/in (t/truncate (t/instant 1552786820310) :seconds) (t/zone "Europe/London"))
; Execution error (Error) at (<cljs repl>:1) .
; unsupported ZoneId:Europe/London

Extending API to Instant

I'm using this project with Datomic, which can only store java.time.Date values natively. So I do this sort of thing all the time.

(t/inst (t/+ (t/instant #inst "...") (t/new-duration 10 :minutes))) => #inst "..."

Would you be interested in a PR that extends the API to do this conversion internally for inst's? So then we can just do this

(t/+ #inst "..." (t/new-duration 10 :minutes)) => #inst "..."

t/month doesn't work for date-time values

t/month doesn't work for date-time values, but t/year and t/day-of-month do:

=> (t/year (t/date-time))
#time/year "2019"

=> (t/day-of-month (t/date-time))
9

=> (t/month (t/date-time))
Execution error (IllegalArgumentException) at tick.core/eval43424$fn$G (core.cljc:152).
No implementation of method: :month of protocol: #'tick.core/IExtraction found for class: java.time.LocalDateTime
class java.lang.IllegalArgumentException

get circleci build working

I think it was set up when this was a lein project
can it use the make test ?
add a badge to the readme

No result when scheduled function has wrong arity

Hi there, I wondered what should the behaviour be when I try to schedule a function with the wrong arity? It becomes clear reasonably quickly that functions that are the first argument to schedule/schedule should take one argument, being the specific tick of the clock that triggered the call. But if I pass a zero argument function, nothing happens at all, not even any side-effects, indicating that the function never gets called. I presume some ArityException happens internally, but I never see it.

I'm not sure if there should be an error message from tick in this case, or maybe the user can use one of Clojure/Java's existing mechanisms to report these errors.

date-time -> inst conversion doesn't respect clock

Converting a date-time to a inst doesn't respect a clock binding. It uses the system default zone instead.

(t/with-clock (t/in (t/clock) "Pacific/Honolulu")
 (-> (t/date-time "2019-08-07T12:00") (t/inst)))
=> #inst"2019-08-07T10:00:00.000-00:00"

The expected answer is 22:00

(-> (t/zoned-date-time "2019-08-07T12:00-10:00[Pacific/Honolulu]") (t/inst))
=> #inst"2019-08-07T22:00:00.000-00:00"

The reverse conversion does respect the clock

(t/with-clock (t/in (t/clock) "Pacific/Honolulu")
              (t/zoned-date-time #inst"2019-08-07T22:00"))
=> #time/zoned-date-time"2019-08-07T12:00-10:00[Pacific/Honolulu]"

If you agree this is an error I'd be happy to provide a patch.

Publish API docs

@martinklepsch suggested it would be helpful to have API docs published for Tick.

There's a handy script that I and others have been using that makes it trivial to generate docs with codox, and publish them to gh-pages. I explain things a bit more in this thread.

Would you be interested to have this for Tick? If so I can provide a PR that adds the script, codox, and a link to the API docs from the README. After that it's up to you to simply run ./generate_docs.

Thanks!

Consider using the Closure Library for CLJS

js-joda is quite a gigantic library and just by including it you are adding almost 500KB of JS to your build. The Closure Library itself actually contains a whole bunch of utilities for working Data/Time data and unlike js-joda it is fully DCE compatible. You can find the code in the goog.i18n.* namespaces

I uploaded a sample build report generated by shadow-cljs to show how huge the added code is. Something also includes cljs.pprint which should be removed. The report was generated for this project which itself contains barely any code.

Apologies if this was considered before and rejected but code size is important for Browser builds and this is entirely too big (IMHO).

new-date doesn't work anymore on latest release 0.4.15-alpha

Since 0.4.15-alpha, basic constructor doesn't work anymore with IllegalArgumentException thrown when run on JVM. Just bumping the version from 0.4.14-alpha to 0.4.15-alpha throws the error.
Example:

(t/new-date 2019 7 17)
Execution error (IllegalArgumentException) at cljc.java-time.local-date/of (local_date.cljc:9).
no corresponding java.time method with these args

Bring tick.deprecated.schedule back from the dead?

Hi friends, I'm in need of a scheduler and believe the two ITicker implementations in tick.deprecated.schedule are close to what I need from an API and functionality perspective. If I were to work on them, would there be a desire to bring them back from deprecated status or should I make my own scheduler library inspired by them that builds on top of the current tick public api?

interval/disjoin implementation

Hi!

I see that disjoin is only partially implemented, but there's still code that looks interesting in the TODO comment. Is it a work in progress or is that something that you would like to see a PR for?

Getting started doc?

Any getting started section in the readme? That will greatly ease the process of using the package.

API Enhancement: Use DateTimeFormatter for parsing

The java.time API allows using a DateTimeFormatter to parse dates, e.g.

(LocalDate/parse "8/17/2011" (t/formatter "M/d/y"))
=> #time/date"2011-08-17"

It would be nice if the tick functions like parse, date, etc. accepted a DateTimeFormatter as an optional second argument

More polymorphic <,>, max, min and the missing 'coincide'

Wouldn't it make sense everything coercible to Instant (ZondedDT, the good old java.util.Date, maybe even String and Number) be comparable with each other accepting as a second parameter for <,>, min, max? This raises the question, although a bit independent, of having new, missing op in ITimeComparision like 'same-instant' or 'coincide'. (Well, for non-locals.)

t/month doesn't work on year-month value

The t/month function works on dates and instants, but doesn't work on year-month values:

=> (t/month (t/today))  ; #time/date "2019-07-08"
#time/month "JULY"

=> (t/month (t/now))  ; #time/instant "2019-07-09T06:27:28.983049Z"
#time/month "JULY"

=> (t/month (t/year-month (t/now)))  ; #time/year-month "2019-07"
Execution error (IllegalArgumentException) at tick.core/eval43248$fn$G (core.cljc:152).
No implementation of method: :month of protocol: #'tick.core/IExtraction found for class: java.time.YearMonth
class java.lang.IllegalArgumentException

api for creating specs

specs for all the java.time domain types and intervals

fns to create generators for these, along the lines of clojure.spec/inst-in

not really thought about coercion yet

Operations involving equality fail with java.time.Month in ClojureScript

❯ clj -Sdeps '{:deps {tick {:mvn/version "RELEASE"} org.clojure/clojurescript {:mvn/version "1.10.516"}}}' -m cljs.main
Downloading: tick/tick/maven-metadata.xml from https://repo.clojars.org/
ClojureScript 1.10.516
cljs.user=> (require '[tick.alpha.api :as t])
nil
cljs.user=> (require 'time-literals.data-readers)
nil
cljs.user=> #{#time/month "MARCH" #time/month "APRIL"}
Execution error (Error) at (<cljs repl>:1).
x__$1.equals is not a function

group-by-intervals-test fails

make test fails with:

FAIL in (group-by-intervals-test) (interval_test.cljc:555)
p and s
expected: (= {(t/year 2017) [(ti/new-interval (t/date-time "2017-12-20T00:00") (t/date-time "2018-01-01T00:00"))], (t/year 2018) [(ti/new-interval (t/date-time "2018-01-01T00:00") (t/date-time "2018-01-10T00:00"))]} (ti/group-by (t/divide (ti/bounds (t/year 2016) (t/year 2019)) t/year) [(ti/new-interval (t/date-time #inst "2017-12-20T00:00:00.000-00:00") (t/date-time #inst "2018-01-10T00:00:00.000-00:00"))]))
  actual: (not (= {#jsr310/year "2017" [#:tick{:beginning #jsr310/date-time "2017-12-20T00:00", :end #jsr310/date-time "2018-01-01T00:00"}], #jsr310/year "2018" [#:tick{:beginning #jsr310/date-time "2018-01-01T00:00", :end #jsr310/date-time "2018-01-10T00:00"}]} {#jsr310/year "2017" [#:tick{:beginning #jsr310/date-time "2017-12-20T02:00", :end #jsr310/date-time "2018-01-01T00:00"}], #jsr310/year "2018" [#:tick{:beginning #jsr310/date-time "2018-01-01T00:00", :end #jsr310/date-time "2018-01-10T02:00"}]}))

It looks like (t/date-time "2017-12-20T00:00") returns #jsr310/date-time"2017-12-20T00:00", while (t/date-time #inst "2017-12-20") returns #jsr310/date-time"2017-12-20T02:00" (the same time in my local time zone).

Does #inst -> LocalDateTime conversion work correctly?

Stopping should cancel any running jobs

(let [tl (tick.timeline/timeline
          (tick.timeline/periodic-seq
           (tick.clock/now)
           (tick.core/minutes 1)))
      job-fn (fn [tick]
               (doseq [idx (range 15)]
                 (println idx tick)
                 (Thread/sleep 1000)))]
  (def sched (tick.schedule/schedule job-fn tl))
  (tick.schedule/start sched (tick.clock/clock-ticking-in-seconds)))

(tick.schedule/stop sched)

If you evaluate the let and then stop the schedule you will still see the remaining println calls of the initial call to job-fn. I think these probably should get cancelled as well.

schedule/start does not skip times in the past

The schedule examples typically start from just-now times or future times.
I did a quick test to see what would happen if I wanted to use tick for cron-like scheduling as an alternative to immutant.scheduling, which currently isn’t timezone-aware.
However, it appears that tick’s scheduler also fires for times in the past.
I expected these to be ignored, or is there a use case for scheduling times in the past?

(Haven't yet tested what resume does.)

(def tl  (tick.timeline/timeline (tick.timeline/periodic-seq
  (.. (java-time/local-date "2017-08-17") (atTime 9 41) (atZone (java-time/zone-id "Europe/Oslo")))
  (hours 1))))

(def sch (tick.schedule/schedule println tl))

;; this rapidly fires 6 ticks, expected 0
(tick.schedule/start sch (tick.clock/fixed-clock (java-time/zoned-date-time 2017 8 17 15 30)))

t/concur fails

(t/concur
  #:tick{:beginning #time/instant"2000-01-01T01:00:01.011Z", :end #time/instant"2000-01-01T02:00:01.011Z"}
  #:tick{:beginning #time/instant"2000-01-01T00:00:00.003Z", :end #time/instant"2000-01-01T01:00:00.003Z"}
  #:tick{:beginning #time/instant"2000-01-01T01:00:01.179Z", :end #time/instant"2000-01-01T02:00:01.179Z"})

Fails with:

No implementation of method: :< of protocol: #'tick.core/ITimeComparison found for class: nil

Because: tick.interval/relation cannot handle nil, which it will get in the example above.

I worked around it by doing:

(defn safe-concur
  ([] nil)
  ([x] x)
  ([x & args]
   (reduce
     (fn safe-concur-check [x y]
       (and
         (and x y)
         (tick.interval/concur x y)))
     x args)))

Transit Encoding

First off, thank you for the fantastic library!

Since we have literals for the various values, it can be handy to encode/decode them in transit+json. Then you can communicate them between client and server.

I defined and installed these handlers for LocalDate and verified they worked with sente.

#?(:cljs
   (deftype LocalDateHandler []
     Object
     (tag [_ _] "time/date")
     (rep [_ r] (str r))
     (stringRep [_ _] nil)))

#?(:clj
   (deftype LocalDateHandler []
     com.cognitect.transit.WriteHandler
     (tag [_ _] "time/date")
     (rep [_ r] (str r))
     (stringRep [_ r] (str r))
     (getVerboseHandler [_] nil)))

Does it make sense to have a namespace for transit handlers like these? I figured other people might want this also.

How to get ordinal values for week days?

First of all, thanks for creating tick! This is the most sensible and powerful time API I've come across - I'm really enjoying using it.

One thing I noticed is there doesn't seem to be a way to get ordinal values for week days. The t/day-of-week function returns def'ed constant values like #time/day-of-week "MONDAY", which is nice, but sometimes it is useful to get their ordinal values as well. For example, I was trying to find the beginning and end of the week period surrounding a given date. To do this, I needed to find the distance from the current date to the preceding Sunday and to the following Saturday.

The t/int function works to translate similar named month constants to ordinal values, but it does not work for the day of week constants:

=> (t/int t/JULY)
7

=> (t/int t/MONDAY)
Execution error (ClassCastException) at tick.core/eval43746$fn (core.cljc:250).
class java.time.DayOfWeek cannot be cast to class java.lang.Character (java.time.DayOfWeek and java.lang.Character are in module java.base of loader 'bootstrap')
class java.lang.ClassCastException

Deprecated APIs

It seems like all of the stuff covered in the readme is deprecated when I click through to the API docs. Is it fair to say big changes are underway?

Conversion of integer/long to instant CLJS Error

Within the documentation it says the following two lines are valid:

(require '[tick.alpha.api :as t])
(t/instant (t/new-duration 1531468976048 :millis))
(t/inst (t/new-duration 1531468976 :seconds))

When runing within clojure this works great and results in the proper output of 2018-07-13T08:02:56.048Z

Within my clojurescript repl however It does not work with the following error:

#object[Error Error: No protocol method IConversion.instant defined for type object: PT425408H2M56.048S]
   cljs.core/missing-protocol (jar:file:/home/david/.m2/repository/org/clojure/clojurescript/1.10.520/clojurescript-1.10.520.jar!/cljs/core.cljs:316:4)
   tick.core/instant (jar:file:/home/david/.m2/repository/tick/tick/0.4.17-alpha/tick-0.4.17-alpha.jar!/tick/core.cljc:146:1)
   tick.alpha.api.instant.cljs$core$IFn$_invoke$arity$1 (jar:file:/home/david/.m2/repository/tick/tick/0.4.17-alpha/tick-0.4.17-alpha.jar!/tick/alpha/api.cljc:73:9)
   tick$alpha$api$instant (jar:file:/home/david/.m2/repository/tick/tick/0.4.17-alpha/tick-0.4.17-alpha.jar!/tick/alpha/api.cljc:71:1)

I would expect it to work within both worlds.

Create a period from an interval?

Hi,

Is there a way to create a period from an interval?

If you, for example, want to find out how many months or years there are between two dates, you can't call years or months on the interval as there doesn't seem to be any way to create a period like you can a duration for days, hours, minutes etc.

Thanks

schedule/jobs?

Coming from https://github.com/jarohen/chime (after looking for a job scheduler).

It appears that the schedule namespace is in the deprecated directory; does it mean that tick is no longer able to act as a job scheduler?

Why ZonedDateTime and not Instant

I just tried creating a timeline with an Instant as starting point. The timeline was created without error but the scheduled function never ran. Reading the docs I noticed that it says ZonedDateTime.

Is there something wrong in creating timelines with an Instant as starting point?
Is that something that tick should potentially be able to do?

js-joda-timezone does not get pulled in unless it is explicitly required by caller

Cannot read property ‘length’ of undefined: 2019-08-30T17:00-00:00[US/Eastern], at index: 0
-------
Caused by: TypeError: Cannot read property ‘length’ of undefined
   at Function.createTreeMap (/Users/amostovoy/dev/gr-mismo/target/doo/out/cljsjs/js-joda/development/js-joda.inc.js:5266:62)
   at ZoneIdPrinterParser.parse (/Users/amostovoy/dev/gr-mismo/target/doo/out/cljsjs/js-joda/development/js-joda.inc.js:5213:41)

This happened because it was using ZoneRulesProvider which has getAvailableZoneIds returning [].

Once we required [cljsjs.js-joda-timezone] in our namespace, we saw that js-joda-timezone got pulled into the cljsjs folder and it worked.

cc @ckirkendall

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.