cosmosdb timer trigger not working properly

I have a question about my function application "timertrigger".
I developed this feature to communicate with telegram bot to send messages after api request.
I tried the feature app locally and it worked great. However, when I try to use cosmosdb to store the information, I run into a problem and cannot save the information.
I have set up all the variables and stuff needed to connect my app with telegram and cosmosdb
try:
database_obj = client.get_database_client(database_name)
await database_obj.read()
return database_obj
except exceptions.cosmosresourcenotfounderror:
print("creating database")
return await client.create_database(database_name)
# </create_database_if_not_exists>
# create a container
# using a good partition key improves the performance of database operations.
# <create_container_if_not_exists>
async def get_or_create_container(database_obj, container_name):
try:
todo_items_container = database_obj.get_container_client(container_name)
await todo_items_container.read()
return todo_items_container
except exceptions.cosmosresourcenotfounderror:
print("creating container with lastname as partition key")
return await database_obj.create_container(
id=container_name,
partition_key=partitionkey(path="/lastname"),
offer_throughput=400)
except exceptions.cosmoshttpresponseerror:
raise
# </create_container_if_not_exists>
async def populate_container_items(container_obj, items_to_create):
# add items to the container
family_items_to_create = items_to_create
# <create_item>
for family_item in family_items_to_create:
inserted_item = await container_obj.create_item(body=family_item)
print("inserted item for %s family. item id: %s" %(inserted_item['lastname'], inserted_item['id']))
# </create_item>
# </method_populate_container_items>
async def read_items(container_obj, items_to_read):
# read items (key value lookups by partition key and id, aka point reads)
# <read_item>
for family in items_to_read:
item_response = await container_obj.read_item(item=family['id'], partition_key=family['lastname'])
request_charge = container_obj.client_connection.last_response_headers['x-ms-request-charge']
print('read item with id {0}. operation consumed {1} request units'.format(item_response['id'], (request_charge)))
# </read_item>
# </method_read_items>
# <method_query_items>
async def query_items(container_obj, query_text):
# enable_cross_partition_query should be set to true as the container is partitioned
# in this case, we do have to await the asynchronous iterator object since logic
# within the query_items() method makes network calls to verify the partition key
# definition in the container
# <query_items>
query_items_response = container_obj.query_items(
query=query_text,
enable_cross_partition_query=true
)
request_charge = container_obj.client_connection.last_response_headers['x-ms-request-charge']
items = [item async for item in query_items_response]
print('query returned {0} items. operation consumed {1} request units'.format(len(items), request_charge))
# </query_items>
# </method_query_items>
async def run_sample():
print('aaaa')
print('sss {0}'.format(cosmosclient(endpoint,credential=key)))
async with cosmosclient(endpoint, credential = key) as client:
print('connected to db')
try:
database_obj = await get_or_create_db(client, database_name)
# create a container
container_obj = await get_or_create_container(database_obj, container_name)
family_items_to_create = ["link", "ss", "s", "s"]
await populate_container_items(container_obj, family_items_to_create)
await read_items(container_obj, family_items_to_create)
# query these items using the sql query syntax.
# specifying the partition key value in the query allows cosmos db to retrieve data only from the relevant partitions, which improves performance
query = "select * from c "
await query_items(container_obj, query)
except exceptions.cosmoshttpresponseerror as e:
print('\nrun_sample has caught an error. {0}'.format(e.message))
finally:
print("\nquickstart complete")
async def main(mytimer: func.timerrequest) -> none:
utc_timestamp = datetime.datetime.utcnow().replace(
tzinfo=datetime.timezone.utc).isoformat()
asyncio.create_task(run_sample())
logging.info(' sono partito')
sendnews()
if mytimer.past_due:
logging.info('the timer is past due!')
logging.info('python timer trigger function ran at %s', utc_timestamp)
I have started my function
func host start --port 7072
But I think there is something wrong with the connection to the database, because console.log('connected to db') is not being printed.
It seems that all operations related to cosmosdb are not executed. If there are errors, I don’t know how to solve them.
I don't get any errors in my terminal, but as I said, cosmosdb doesn't seem to work.
I'm not sure if all the necessary information was provided to you. thanks for your help.
Correct answer
I also encountered the same problem when using async functions. It works for me when I use non-async function.
Please check this for reference document
My code:
timetrigger1/__init__.py:
import datetime
import logging
import asyncio
import azure.functions as func
from azure.cosmos import cosmos_client
import azure.cosmos.exceptions as exceptions
from azure.cosmos.partition_key import partitionkey
endpoint = "https://timercosmosdb.documents.azure.com/"
key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
database_name = "todolist"
container_name = "test"
def get_or_create_db(client,database_name):
try:
database_obj = client.get_database_client(database_name)
database_obj.read()
return database_obj
except exceptions.cosmosresourcenotfounderror:
logging.info("creating database")
return client.create_database_if_not_exists(database_name)
def get_or_create_container(database_obj, container_name):
try:
todo_items_container = database_obj.get_container_client(container_name)
todo_items_container.read()
return todo_items_container
except exceptions.cosmosresourcenotfounderror:
logging.info("creating container with lastname as partition key")
return database_obj.create_container_if_not_exists(
id=container_name,
partition_key=partitionkey(path="/id"),
offer_throughput=400)
except exceptions.cosmoshttpresponseerror:
raise
def populate_container_items(container_obj,items):
inserted_item = container_obj.create_item(body=items)
logging.info("inserted item for %s family. item id: %s" %(inserted_item['lastname'], inserted_item['id']))
def read_items(container_obj,id):
item_response = container_obj.read_item(item=id, partition_key=id)
request_charge = container_obj.client_connection.last_response_headers['x-ms-request-charge']
logging.info('read item with id {0}. operation consumed {1} request units'.format(item_response['id'], (request_charge)))
def query_items(container_obj, query_text):
query_items_response = container_obj.query_items(
query=query_text,
enable_cross_partition_query=true
)
request_charge = container_obj.client_connection.last_response_headers['x-ms-request-charge']
items = [item for item in query_items_response]
logging.info('query returned {0} items. operation consumed {1} request units'.format(len(items), request_charge))
def run_sample():
logging.info('aaaa')
client = cosmos_client.cosmosclient(endpoint, key)
logging.info('connected to db')
try:
id= "test"
database_obj = get_or_create_db(client,database_name)
container_obj = get_or_create_container(database_obj,container_name)
item_dict = {
"id": id,
"lastname": "shandilya",
"firstname": "vivek",
"gender": "male",
"age": 35
}
populate_container_items(container_obj,item_dict)
read_items(container_obj,id)
query = "select * from c "
query_items(container_obj, query)
except exceptions.cosmoshttpresponseerror as e:
logging.info('\nrun_sample has caught an error. {0}'.format(e.message))
finally:
logging.info("\nquickstart complete")
def main(mytimer: func.timerrequest) -> none:
utc_timestamp = datetime.datetime.utcnow().replace(
tzinfo=datetime.timezone.utc).isoformat()
run_sample()
logging.info(' sono partito')
logging.info('python timer trigger function ran at %s', utc_timestamp)
output:
functions:
timertrigger1: timertrigger
for detailed output, run func with --verbose flag.
[2024-01-30t09:00:24.818z] executing 'functions.timertrigger1' (reason='timer fired at 2024-01-30t14:30:24.7842979+05:30', id=5499e180-4964-4d7e-b9f2-b024860945dd)
[2024-01-30t09:00:24.822z] trigger details: unscheduledinvocationreason: ispastdue, originalschedule: 2024-01-30t14:30:00.0000000+05:30
[2024-01-30t09:00:25.022z] aaaa
[2024-01-30t09:00:26.387z] connected to db
[2024-01-30t09:00:28.212z] inserted item for shandilya family. item id: test
[2024-01-30t09:00:28.373z] read item with id test. operation consumed 1 request units
[2024-01-30t09:00:28.546z]
quickstart complete
[2024-01-30t09:00:28.548z] python timer trigger function ran at 2024-01-30t09:00:25.008468+00:00
[2024-01-30t09:00:28.547z] sono partito
[2024-01-30t09:00:28.546z] query returned 1 items. operation consumed 1 request units
[2024-01-30t09:00:28.592z] executed 'functions.timertrigger1' (succeeded, id=5499e180-4964-4d7e-b9f2-b024860945dd, duration=3793ms)
[2024-01-30t09:00:29.296z] host lock lease acquired by instance id '000000000000000000000000aae5f384'.
{
"id": "test",
"lastName": "Shandilya",
"firstName": "Vivek",
"gender": "male",
"age": 35,
"_rid": "ey58AO9yWqwCAAAAAAAAAA==",
"_self": "dbs/ey58AA==/colls/ey58AO9yWqw=/docs/ey58AO9yWqwCAAAAAAAAAA==/",
"_etag": "\"01001327-0000-1a00-0000-65b8baac0000\"",
"_attachments": "attachments/",
"_ts": 1706605228
}
The above is the detailed content of cosmosdb timer trigger not working properly. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
SQLAlchemy 2.0 Deprecation Warning and Connection Close Problem Resolving Guide
Aug 05, 2025 pm 07:57 PM
This article aims to help SQLAlchemy beginners resolve the "RemovedIn20Warning" warning encountered when using create_engine and the subsequent "ResourceClosedError" connection closing error. The article will explain the cause of this warning in detail and provide specific steps and code examples to eliminate the warning and fix connection issues to ensure that you can query and operate the database smoothly.
How to automate data entry from Excel to a web form with Python?
Aug 12, 2025 am 02:39 AM
The method of filling Excel data into web forms using Python is: first use pandas to read Excel data, and then use Selenium to control the browser to automatically fill and submit the form; the specific steps include installing pandas, openpyxl and Selenium libraries, downloading the corresponding browser driver, using pandas to read Name, Email, Phone and other fields in the data.xlsx file, launching the browser through Selenium to open the target web page, locate the form elements and fill in the data line by line, using WebDriverWait to process dynamic loading content, add exception processing and delay to ensure stability, and finally submit the form and process all data lines in a loop.
python pandas styling dataframe example
Aug 04, 2025 pm 01:43 PM
Using PandasStyling in JupyterNotebook can achieve the beautiful display of DataFrame. 1. Use highlight_max and highlight_min to highlight the maximum value (green) and minimum value (red) of each column; 2. Add gradient background color (such as Blues or Reds) to the numeric column through background_gradient to visually display the data size; 3. Custom function color_score combined with applymap to set text colors for different fractional intervals (≥90 green, 80~89 orange, 60~79 red,
How to create a virtual environment in Python
Aug 05, 2025 pm 01:05 PM
To create a Python virtual environment, you can use the venv module. The steps are: 1. Enter the project directory to execute the python-mvenvenv environment to create the environment; 2. Use sourceenv/bin/activate to Mac/Linux and env\Scripts\activate to Windows; 3. Use the pipinstall installation package, pipfreeze>requirements.txt to export dependencies; 4. Be careful to avoid submitting the virtual environment to Git, and confirm that it is in the correct environment during installation. Virtual environments can isolate project dependencies to prevent conflicts, especially suitable for multi-project development, and editors such as PyCharm or VSCode are also
python schedule library example
Aug 04, 2025 am 10:33 AM
Use the Pythonschedule library to easily implement timing tasks. First, install the library through pipinstallschedule, then import the schedule and time modules, define the functions that need to be executed regularly, then use schedule.every() to set the time interval and bind the task function. Finally, call schedule.run_pending() and time.sleep(1) in a while loop to continuously run the task; for example, if you execute a task every 10 seconds, you can write it as schedule.every(10).seconds.do(job), which supports scheduling by minutes, hours, days, weeks, etc., and you can also specify specific tasks.
How to handle large datasets in Python that don't fit into memory?
Aug 14, 2025 pm 01:00 PM
When processing large data sets that exceed memory in Python, they cannot be loaded into RAM at one time. Instead, strategies such as chunking processing, disk storage or streaming should be adopted; CSV files can be read in chunks through Pandas' chunksize parameters and processed block by block. Dask can be used to realize parallelization and task scheduling similar to Pandas syntax to support large memory data operations. Write generator functions to read text files line by line to reduce memory usage. Use Parquet columnar storage format combined with PyArrow to efficiently read specific columns or row groups. Use NumPy's memmap to memory map large numerical arrays to access data fragments on demand, or store data in lightweight data such as SQLite or DuckDB.
python logging to file example
Aug 04, 2025 pm 01:37 PM
Python's logging module can write logs to files through FileHandler. First, call the basicConfig configuration file processor and format, such as setting the level to INFO, using FileHandler to write app.log; secondly, add StreamHandler to achieve output to the console at the same time; Advanced scenarios can use TimedRotatingFileHandler to divide logs by time, for example, setting when='midnight' to generate new files every day and keep 7 days of backup, and make sure that the log directory exists; it is recommended to use getLogger(__name__) to create named loggers, and produce
HDF5 Dataset Name Conflicts and Group Names: Solutions and Best Practices
Aug 23, 2025 pm 01:15 PM
This article provides detailed solutions and best practices for the problem that dataset names conflict with group names when operating HDF5 files using the h5py library. The article will analyze the causes of conflicts in depth and provide code examples to show how to effectively avoid and resolve such problems to ensure proper reading and writing of HDF5 files. Through this article, readers will be able to better understand the HDF5 file structure and write more robust h5py code.


