@@ -11,7 +11,11 @@ use prometheus_client::{
1111 registry:: { Metric , Registry } ,
1212} ;
1313use prometheus_client_derive_encode:: { EncodeLabelSet , EncodeLabelValue } ;
14- use std:: sync:: { LazyLock , Mutex } ;
14+ use std:: {
15+ sync:: { LazyLock , Mutex } ,
16+ time:: Duration ,
17+ } ;
18+ use tokio:: time;
1519
1620static REGISTRY : LazyLock < Mutex < Registry > > = LazyLock :: new ( || Mutex :: new ( Registry :: default ( ) ) ) ;
1721
@@ -47,23 +51,24 @@ async fn metrics_handler() -> impl IntoResponse {
4751}
4852
4953#[ derive( Clone , Debug , Hash , PartialEq , Eq , EncodeLabelValue ) ]
50- pub enum Method {
51- Get ,
52- Post ,
54+ pub enum Type {
55+ Request ,
56+ BackgroundTask ,
5357}
5458
5559#[ derive( Clone , Debug , Hash , PartialEq , Eq , EncodeLabelSet ) ]
5660pub struct MethodLabels {
57- pub method : Method ,
61+ pub method : Type ,
5862}
5963
60- static METRIC : LazyLock < Family < MethodLabels , Counter > > =
61- LazyLock :: new ( || register_metric_to_global_registry ( "requests" , "Count of requests" ) ) ;
64+ static METRIC : LazyLock < Family < MethodLabels , Counter > > = LazyLock :: new ( || {
65+ register_metric_to_global_registry ( "requests_and_tasks" , "Count of requests & tasks" )
66+ } ) ;
6267
6368pub async fn some_handler ( ) -> impl IntoResponse {
6469 METRIC
6570 . get_or_create ( & MethodLabels {
66- method : Method :: Get ,
71+ method : Type :: Request ,
6772 } )
6873 . inc ( ) ;
6974 "okay" . to_string ( )
@@ -79,5 +84,18 @@ async fn main() {
7984 . await
8085 . unwrap ( ) ;
8186
82- axum:: serve ( listener, router) . await . unwrap ( ) ;
87+ tokio:: join!( axum:: serve( listener, router) , background_task( ) ) ;
88+ }
89+
90+ async fn background_task ( ) {
91+ let mut interval = time:: interval ( Duration :: from_secs ( 2 ) ) ;
92+ loop {
93+ interval. tick ( ) . await ;
94+ let current = METRIC
95+ . get_or_create ( & MethodLabels {
96+ method : Type :: BackgroundTask ,
97+ } )
98+ . inc ( ) ;
99+ println ! ( "executed task: {current} times" ) ;
100+ }
83101}
0 commit comments